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 8841671
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T10:46:43+00:00 2026-06-14T10:46:43+00:00

I am trying the EF5 CodeFirst and cannot get the simple setup to work

  • 0

I am trying the EF5 CodeFirst and cannot get the simple setup to work ;(

I have two classes Foo and Bar where Bar represent lookup table.

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Bar Bar { get; set; }

}

public class Bar
{
    public int Id { get; set; }
    public string Description { get; set; }
}

public class MyDbContext : DbContext
{
    static MyDbContext()
    {
        Database.SetInitializer<MyDbContext>(null);
    }

    public MyDbContext(): base("testEF"){}

    public DbSet<Foo> Foos { get; set; }
    public DbSet<Bar> Bars { get; set; }
}

Now I have created a static class that serves as DataAccess Layer – in real-world application it will be on different physical tier

public static class DataAccess
{
    public static Bar GetBarById(int id)
    {
        using (var db = new MyDbContext())
        {
            return db.Bars.SingleOrDefault(b => b.Id == id);
        }
    }

    public static Foo InsertFoo(Foo foo)
    {
        using (var db = new MyDbContext())
        {
            db.Foos.Add(foo);

            db.SaveChanges();
        }
        return foo;
    }
}

I am initializing the DB with seed method:

internal sealed class Configuration : DbMigrationsConfiguration<testEF.MyDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }
    protected override void Seed(testEF.MyDbContext context)
    {
            context.Bars.AddOrUpdate(
                new Bar { Description = "Bar_1" },
                new Bar { Description = "Bar_2" }

                );
    }
}

This creates two records in Bars table. So far so good…

Here is my Main function

static void Main(string[] args)
{
    var bar1 = DataAccess.GetBarById(1); 

    var foo = new Foo
    {
        Name = "Foo_1",
        Bar = bar1
    };

    DataAccess.InsertFoo(foo);

}

After the app runes there is a record in the Foos table:

Id       Name    Bar_Id
1        Foo_1   3   

Why Bar_Id is 3? The EF actually inserted new record to Bars table!

Id  Description
1   Bar_1
2   Bar_2
3   Bar_1

What I am doing wrong?

UPDATE:
I have found a workaround – to attach Bar property prior to inserting the record:

public static Foo InsertFoo(Foo foo)
{
    using (var db = new MyDbContext())
    {
        db.Bars.Attach(foo.Bar);

        db.Foos.Add(foo);

        db.SaveChanges();
    }
    return foo;
}

It is working now but this is more like a hack than a valid solution…
In real-world application the complexity of the objects could become a huge problem.
I am open to better solutions

  • 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-14T10:46:45+00:00Added an answer on June 14, 2026 at 10:46 am

    The problem is that bar1 comes from a different data context. Your InsertFoo method implicitly adds it to the second context by building a relationship with the Foo. You want these two to share a context. So use a single context for the whole scope of the Main method.

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

Sidebar

Related Questions

Trying a simple project to create my own (very basic) data binding. I have
Trying to create a data.frame like this: a = foo bar = data.frame(a =
I'm trying to use the CodeFirst data migrations in EF5 with a table that
I'm currently working in asp.net mvc 4 with EF5 and I'm trying to get
I am trying to update my repository to EF5 but have encountered a few
trying to get my first HTML/CSS uni assignment sorted but have become a bit
Trying to do something really simple, but can't figure out the syntax. I have
Trying to send a PHP email the easy way but I cannot work out
trying to solve a problem and i cant get why it wont work. I'm
Just trying to confirm an impression: it seems enums in EF5 + Code First

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.