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

  • Home
  • SEARCH
  • 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 8345269
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T06:37:36+00:00 2026-06-09T06:37:36+00:00

I have following entity framework code first code. The tables are created and data

  • 0

I have following entity framework code first code. The tables are created and data is inserted. However there are duplicate records in Club table.

My operations are:-

  1. Create clubs using club creation app

  2. Create persons using person app

How to avoid the duplicate entry?

enter image description here

    static void Main(string[] args)
    {
        Database.SetInitializer<NerdDinners>(new MyInitializer());

        CreateClubs();
        InsertPersons();

    }

    public static void CreateClubs()
    {

        string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30";
        using (var db = new NerdDinners(connectionstring))
        {

            Club club1 = new Club();
            club1.ClubName = "club1";

            Club club2 = new Club();
            club2.ClubName = "club2";

            Club club3 = new Club();
            club3.ClubName = "club3";

            db.Clubs.Add(club1);
            db.Clubs.Add(club2);
            db.Clubs.Add(club3);

            int recordsAffected = db.SaveChanges();


        }
    }

    public static Club GetClubs(string clubName)
    {
        string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30";
        using (var db = new NerdDinners(connectionstring))
        {

            //var query = db.Clubs.Where(p => p.ClubName == clubName);
            var query = db.Clubs.SingleOrDefault(p => p.ClubName == clubName);
            return query;
        }
    }

    public static void InsertPersons()
    {
        string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30";
        using (var db = new NerdDinners(connectionstring))
        {

            Club club1 = GetClubs("club1");
            Club club2 = GetClubs("club2");
            Club club3 = GetClubs("club3");

            Person p1 = new Person();
            p1.PersonName = "Person1";

            Person p2 = new Person();
            p2.PersonName = "Person2";

            List<Club> clubsForPerson1 = new List<Club>();
            clubsForPerson1.Add(club1);
            clubsForPerson1.Add(club3);

            List<Club> clubsForPerson2 = new List<Club>();
            clubsForPerson2.Add(club2);
            clubsForPerson2.Add(club3);

            p1.Clubs = clubsForPerson1;
            p2.Clubs = clubsForPerson2;

            db.Persons.Add(p1);
            db.Persons.Add(p2);

            int recordsAffected = db.SaveChanges();


        }
    }

Domain

public class Person
{
    public int PersonId { get; set; }
    public string PersonName { get; set; }
    public virtual ICollection<Club> Clubs { get; set; }
}

public class Club
{
    public int ClubId { get; set; }
    public string ClubName { get; set; }
    public virtual ICollection<Person> Members { get; set; }
}

//System.Data.Entity.DbContext is from EntityFramework.dll
public class NerdDinners : System.Data.Entity.DbContext
{

    public NerdDinners(string connString): base(connString)
    { 

    }

    protected override void OnModelCreating(DbModelBuilder modelbuilder)
    {
         //Fluent API - Plural Removal
        modelbuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

    public DbSet<Person> Persons { get; set; }
    public DbSet<Club> Clubs { get; set; }

}
  • 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-09T06:37:37+00:00Added an answer on June 9, 2026 at 6:37 am

    The problem is that you create more contexts.

    First you create the clubs. It’s ok. But when you create the persons, you fetch the clubs via GetClubs, but for each club you dispose the actual entity framework context so you end up with detached entities. At InsertPersons you add detached club entities to the new persons so the actual context will think that the clubs are new clubs.

    So when you add a club to a person you actually create new clubs.

    This is because entity framework tracks the changes and manages the entities per context. If you add an entity to a context which does not contains it yet then it will treat like a new entity.

    Actually, you should do something like this (not tested):

    static void Main(string[] args)
    {
        Database.SetInitializer<NerdDinners>(new MyInitializer());
    
        string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30";
        using (var db = new NerdDinners(connectionstring))
        {
            CreateClubs(db);
            InsertPersons(db);
        }
    
    }
    
    public static void CreateClubs(NerdDinners db)
    {
        Club club1 = new Club();
        club1.ClubName = "club1";
    
        Club club2 = new Club();
        club2.ClubName = "club2";
    
        Club club3 = new Club();
        club3.ClubName = "club3";
    
        db.Clubs.Add(club1);
        db.Clubs.Add(club2);
        db.Clubs.Add(club3);
    
        int recordsAffected = db.SaveChanges();
    }
    
    public static Club GetClubs(string clubName, NerdDinners db)
    {
        //var query = db.Clubs.Where(p => p.ClubName == clubName);
        var query = db.Clubs.SingleOrDefault(p => p.ClubName == clubName);
        return query;
    }
    
    public static void InsertPersons(NerdDinners db)
    {
        Club club1 = GetClubs("club1", db);
        Club club2 = GetClubs("club2", db);
        Club club3 = GetClubs("club3", db);
    
        Person p1 = new Person();
        p1.PersonName = "Person1";
    
        Person p2 = new Person();
        p2.PersonName = "Person2";
    
        List<Club> clubsForPerson1 = new List<Club>();
        clubsForPerson1.Add(club1);
        clubsForPerson1.Add(club3);
    
        List<Club> clubsForPerson2 = new List<Club>();
        clubsForPerson2.Add(club2);
        clubsForPerson2.Add(club3);
    
        p1.Clubs = clubsForPerson1;
        p2.Clubs = clubsForPerson2;
    
        db.Persons.Add(p1);
        db.Persons.Add(p2);
    
        int recordsAffected = db.SaveChanges();
    }
    

    Of course you should refactor the structure of this code, but please notice that I use only one EF context for my operations.

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

Sidebar

Related Questions

I have following C# code that uses Entity Framework Code First approach. The tables
I have the following table created using Entity Framework Code First approach. How do
I have the following classes in an Entity Framework 4.3 Code-First Model for MVC3:
Using the Entity Framework Code First paradigm I have defined the following objects and
I am using MVC3 with Entity Framework Code First. I have the following model.
I am using Entity Framework Code First Approach. I have following code to insert
I am following the database approach first; I have created the tables in my
I have been using Entity Framework CTP with Code-First as in this tutorial by
I have the following tables represented in my Entity Framework diagram (.edmx file) Users
Is there a way in Entity Framework 4 (using CTP4 and Code First if

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.