Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7976275
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T08:52:33+00:00 2026-06-04T08:52:33+00:00

I’m having troubles with creating and/or storing m:n relationship with EF 4.3 Code first

  • 0

I’m having troubles with creating and/or storing m:n relationship with EF 4.3 Code first

So the first entity Publication is defined as with some other internal scalar properties:

    public class Publication : IDataErrorInfo{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PublicationId { get; set; }

    [InverseProperty("Publications")]
    public virtual ICollection<Group> Groups { get; set; }

and the other class in the same way:

    public class Group : IDataErrorInfo {

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int GroupId { get; set; }

    [InverseProperty("Groups")]
    public ICollection<Publication> Publications { get; set; }

which according to numerous articles should be fine.

There are several problems I occur. AT first:

  • If I create a new publication and assert it some Groups. All is stored to the db. But then I restart the program, the same particular publication has ICollection set to null. Therefore the information about relationship with Group has been deleted.I don’t know why 🙁
  • When I try to update exisiting Publication entry with Group relationship, the DBUpdateException is thrown with the following text:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types

In the inner exception is the same, and in the inner exception of this one is the following:

Violation of PRIMARY KEY constraint ‘PK_Publicat_3AF5D6A10AD2A005′. Cannot insert duplicate key in object ‘dbo.PublicationGroups’.
The statement has been terminated.

I’m asserting the the new values of the Publication as follows:

var entry = db.Publications.First(a => a.PublicationId == publKey);
entry.Groups = db.Groups.
                Where(a => groupKeys.Contains(a.GroupId)).
                Select(b => b).
                ToList();

where publKey is the key of the edited entity and groupKeys is the List of GroupId which should be the publication be related to.

after calling db.SaveContext() the exception is thrown

This topic has been covered by numerous articles, but I didn’t find any solution. All of the examples are using the same code, but apparently I’m missing something. I’m using SQL Ce 4.0 as the persistance data storage.

Thank you guys for answer, I’m dealing with it since yesterday, but don’t why this happens

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T08:52:34+00:00Added an answer on June 4, 2026 at 8:52 am

    Are you calling .Save after you’ve added the groups to the database? Otherwise when you try to add the groups to the publication, they won’t actually be in the DbSet yet. The following code works for me – perhaps you could clarify how it differs from yours?

    public class Publication
    {
        public int PublicationId { get; set; }
        public string PublicationName { get; set; }
        public virtual ICollection<Group> Groups { get; set; }
    }
    
    public class Group
    {
        public int GroupId { get; set; }
        public string GroupName { get; set; }
        public ICollection<Publication> Publications { get; set; }
    }
    
    public class Context : DbContext
    {
        public DbSet<Publication> Publications { get; set; }
        public DbSet<Group> Groups { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Context>());
    
            Context context = new Context();
    
            // Only add the groups if it's a new database
            if (!context.Groups.Any())
            {
                context.Groups.Add(new Group { GroupName = "Group 1" });
                context.Groups.Add(new Group { GroupName = "Group 2" });
                context.SaveChanges();
            }
    
            if (context.Publications.Any())
            {
                Console.WriteLine("At startup, P1 is in groups " + String.Join(", ", context.Publications.First().Groups.Select(g => g.GroupName)));
            }
    
            // Add publication
            Publication p;
            p = new Publication();
            p.Groups = context.Groups.ToList();     // Add to all existing groups
            context.Publications.Add(p);
            context.SaveChanges();
    
            Console.WriteLine("P1 is in groups " + String.Join(", ", context.Publications.First().Groups.Select(g => g.GroupName)));
        }
    }
    

    (Code Updated to use SqlCe provider)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
We're building an app, our first using Rails 3, and we're having to build
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.