Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework automatically assigns foreign key ?

I've come accross the following "issue" (it might just be a feature but that would be quite a strange one). Using Entity Framework 5, when inserting an entity without specifying the linked entity through foreign key, EF automatically assigns the value to the related entity (if inserted at the same moment.

Alright, that's not very clear, so here's some code that reproduces the behavior :

[TestClass]
public class TestEntityFramework
{
    [TestMethod]
    public void Test()
    {
        using (var context = new TestDataContext())
        {
            context.Foos.Add(new Foo { FooProp = "FooProp"});                
            context.Bars.Add(new Bar {BarProp = "BarProp"});                
            context.SaveChanges();
        }
    }       
}


public class Foo
{
    [Key]
    public int Id { get; set; }

    public string FooProp { get; set; }
}

public class Bar
{
    [Key]
    public int Id { get; set; }

    public int FooId { get; set; }
    [ForeignKey("FooId")]
    public virtual Foo Foo { get; set; }

    public string BarProp { get; set; }
}

public class TestDataContext : DbContext
{      
    public virtual IDbSet<Foo> Foos { get; set; }
    public virtual IDbSet<Bar> Bars { get; set; }        
}

The Test method surprisingly works, no conflict.

The Bar entity inserted gets linked to the Foo entity inserted at the same time even though I didn't specify it.

However following codes both raises foreign key exceptions :

[TestMethod]
public void Test()
{
    using (var context = new TestDataContext())
    {
        context.Foos.Add(new Foo { FooProp = "FooProp"});
        context.SaveChanges();
        context.Bars.Add(new Bar {BarProp = "BarProp"});                
        context.SaveChanges();
    }
}

[TestMethod]
public void Test2()
{
    using (var context = new TestDataContext())
    {
        context.Foos.Add(new Foo { FooProp = "FooProp" });
        context.Foos.Add(new Foo { FooProp = "FooProp2" });                
        context.Bars.Add(new Bar { BarProp = "BarProp" });
        context.SaveChanges();
    }
}     

Anyone knows if that behavior is expected ? Any thoughts ?

Thanks

like image 903
Etienne Avatar asked Jul 13 '26 23:07

Etienne


1 Answers

My guess is when you create them both before saving they both have an ID of 0. When you create a Bar it's FooId is 0 which "connects it" to the Foo. When you save them separately the context assigns an ID other than 0 to the Foo, and when you create the Bar it's FooID of 0 does not connect it to an existing Foo and thus you get an exception.

like image 157
D Stanley Avatar answered Jul 15 '26 11:07

D Stanley