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
/***
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!