A bit of a mystery has popped up with EF5 and non-null strings in the schema. For example, say we have this simple user table:
CREATE TABLE Users
(
UserID INT PRIMARY KEY NOT NULL IDENTITY(1,1),
UserName VARCHAR(50) NOT NULL,
UserFirst VARCHAR(50) NULL,
UserLast VARCHAR(50) NULL
)
... and I create a POCO class to represent it. This all works fine. I can retrieve and create data, however update has caused some serious pain. Say for a moment that I want to update a given user's first name:
User user = new User { UserID = 12345 };
context.Users.Attach(user);
user.FirstName = "SomethingElse";
context.SaveChanges();
This should work. After attachment, the non-nullable UserName
is null. Which should be fine - I'm not trying to change it, and the change detection states that the value is unchanged. However, when I call SaveChanges
, a DB validation exception is thrown stating the UserName
is invalid.
So, from this, two questions:
- Am I doing something egregiously wrong? I'm entirely willing to believe my understanding of entity framework is flawed.
- Why is the change state by property not used at save-time? I'm aware of
context.Configuration.ValidateOnSaveEnabled
, but I don't think simply turning validation off is a valid answer. Is there another similar option I can lean on?