一對多的關係
UserType 屬於許多使用者< - >使用者有一個 UserType
單向導航屬性需要
public class UserType
{
public int UserTypeId {get; set;}
}
public class User
{
public int UserId {get; set;}
public int UserTypeId {get; set;}
public virtual UserType UserType {get; set;}
}
Entity<User>().HasRequired(u => u.UserType).WithMany().HasForeignKey(u => u.UserTypeId);
單向導航屬性可選(外來鍵必須是 Nullable
型別)
public class UserType
{
public int UserTypeId {get; set;}
}
public class User
{
public int UserId {get; set;}
public int? UserTypeId {get; set;}
public virtual UserType UserType {get; set;}
}
Entity<User>().HasOptional(u => u.UserType).WithMany().HasForeignKey(u => u.UserTypeId);
雙向導航屬性(必要/可選根據需要更改外來鍵屬性)
public class UserType
{
public int UserTypeId {get; set;}
public virtual ICollection<User> Users {get; set;}
}
public class User
{
public int UserId {get; set;}
public int UserTypeId {get; set;}
public virtual UserType UserType {get; set;}
}
需要
Entity<User>().HasRequired(u => u.UserType).WithMany(ut => ut.Users).HasForeignKey(u => u.UserTypeId);
可選的
Entity<User>().HasOptional(u => u.UserType).WithMany(ut => ut.Users).HasForeignKey(u => u.UserTypeId);