When I have this simple model:
public class User
{
// Primary key
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
[Required]
public Int32 FailedPasswordAttemptCount { get; set; }
[Required]
public Language Language { get; set; }
}
public class Language
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid LanguageId { get; set; }
[MaxLength(30)]
public String LocaleName { get; set; }
}
And I do this code:
var user = context.Users.Single(u => u.UserId == userId);
user.FailedPasswordAttemptCount++;
context.SaveChanges();
It will throw an DbEntityValidationException expception The Language field is required..
Technically this is true because the property is marked as required and because the Language property is null when fetched from the database (no lazy or eager loading).
But how do I change this behaviour?
- I don’t want to disable validation completely
- I don’t want to lazy / eager load the field
- I don’t want to remove the Required tag from the model
What other options are out there?
You can prevent this by adding the primitive FK field (probably
LanguageId) to yourUserclass. This is not uncommon in entity framework. There are more occasions where getting or setting the primitive property saves work or unnecessary (lazy) loading.