EF 4.1 Code First: Why is EF not setting this navigation property?

后端 未结 1 1152
我在风中等你
我在风中等你 2020-12-11 23:34

Here\'s a sample scenario that illustrates the problem I am having.

Here is the DB script to generate the database in SQL 2008:

USE [master]
GO

/***         


        
1条回答
  •  失恋的感觉
    2020-12-12 00:30

    I don't have a great answer to your question but I'll give it a shot anyway.

    Basically, you can't initialize the Schedule property in the constructor. By doing this, EF thinks that the property has been modified (set to a new value) and will not attempt to overwrite it. In fact, if you add another context.SaveChanges() before the asserts in your code, you'll see that EF tries to insert the new Schedule entity you created in the constructor.

    The only workaround I can suggest is to initialize the property manually outside the class or, maybe better, create an alternate Customer constructor and make the default one protected or private:

    public class Customer
    {
        public Customer(string name)
        {
            Name = name;
            Schedule = new Schedule();
        }
    
        protected Customer() { }
    
        public int ID { get; set; }
        public string Name { get; set; }
        public int ScheduleID { get; set; }
        public Schedule Schedule { get; set; }
        public byte[] Version { get; set; }
    }
    

    EF will use the default constructor, but you can use the other one in your code.

    I get what you mean about how this seems like a bug but I also kind of understand why EF does what it does... I guess I'm on the fence about it.

    In any case, good luck!

    0 讨论(0)
提交回复
热议问题