I have the following setup, abridged for brevity:
public abstract class AuditableEntity
{
public int Id { get; set; }
public Login Login { get; set; } // Login that create this identity.
}
public class Login: AuditableEntity
{
public Security Security { get; set; }
public Guid SessionGuid { get; set; }
}
public class Security: AuditableEntity
{
public string UserName { get; set; }
public string PasswordHash { get; set; }
}
Now Login is only not required on the Login entity itself. In fact it doesn’t belong in that table and I ignore it thus:
modelBuilder.Entity<Login>().Ignore(l => l.Login);
I want it as required on all other tables, but when I e.g. try and make it required on User:
modelBuilder.Entity<Security.Security>().Property(p => p.Login).IsRequired();
I get a compile error, “The type ‘Login’ must be a non-nullable value type in order to use it as parameter ‘T'”. I note that I am allowed to use it as parameter ‘T’ in the Ignore call before, so I assume this is some other, hidden T.
My immediately apparent solutions are not very elegant:
- Use an FK value and not a reference poperty for
Loginin inAuditableEntity. - Create a new base class without
Login, and another derived from that that addsLogin, then inherit my Login class from the highest base, and all other classes from its immediate descendant.
Is there some better way of doing this?
You are using property syntax for native SQL properties. You actually want to use Nav property syntax such as
.HasRequired(t=>t.Login).WithMany()or something similarSee http://msdn.microsoft.com/en-us/library/hh295843(v=vs.103).aspx, and the Configuring a Relationship with One Navigation Property section