开发者

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())
        {
  开发者_如何学C          CmsContent myContent = context.CmsContents.FirstOrDefault(x => x.ContentId == contentId);
            CmsJob myJob = context.CmsJobs.FirstOrDefault(x => x.JobId == jobId);
            myJob.CmsContents.Add(myContent);
        }


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.


That's because you haven't saved changes. Try this:

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);
        context.SaveChanges();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜