1

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);
        }

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ladislav Mrnka, I understand now. Thanks for your time.
2

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();
    }

3 Comments

I get his error with your code: Unable to update the EntitySet 'CmsJobsContents' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
@GibboK.What is this CmsJobsContents table? Is it a junction table?
This is because the junction table, which used for the many-to-many relation between CmsContents and CmsJobs,is not updated. Make the keys of both the tables a composite key in the CmsJobsContents table. Hopefully this would resolve the issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.