Search code examples
entity-frameworkentity-relationship

Add an Object to Entity Framework using a navigational property


Hi I use C# and EF 4.

I have two Entities CmsContent and CmsJob. CmsJob has a navigational property to CmsContent.

I need add a CmsContent Object to CmsJob using the navigational property.

My code run with no error but I cannot persist the new entry om DataBase.

Could you tell me what I'm doing wrong? Please provide me an example of code. Thanks for your support!

       using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
        {
            CmsContent myContent = context.CmsContents.FirstOrDefault(x => x.ContentId == contentId);
            CmsJob myJob = context.CmsJobs.FirstOrDefault(x => x.JobId == jobId);
            myJob.CmsContents.Add(myContent);
        }

Solution

  • Based on comments under @Hasan's answer you have incorrectly defined database. Your Job and Content are in many-to-many relation so you have junction table called CmsJobsContents but this table is missing primary key. Because of that it is read-only for EF and you cannot create new relations in your application. You must go to your database and mark both FKs in the CmsJobsContents as primary keys. After that update your model from database and you should be able to save changes.