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

ぃ、小莉子 提交于 2019-11-28 14:02:56

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!