2
假設我有這些表:實體框架流利的API映射
Role
- RoleId
- Name
UserRole
- UserId
- RoleId
User
- UserId
- Username
UserEmail
- UserId
- EmailId
- IsPrimary
Email
- EmailId
- Address
現在我的模型,應該是這個樣子:
public class Role {
public int RoleId { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class User {
public int UserId { get; set; }
public string Username { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual ICollection<UserEmail> UserEmails { get; set; }
}
public class UserEmail {
public int UserId { get; set; }
public int EmailId { get; set; }
public bool IsPrimary { get; set; }
public virtual User User { get; set; }
public virtual Email Email { get; set; }
}
public class Email {
public int EmailId { get; set; }
public string Address { get; set; }
public virtual ICollection<UserEmail> UserEmails { get; set; }
}
這些都是常見的和具體的事情我想在這種情況下做:
添加主鍵:
modelBuilder.Entity<Role>().HasKey(q => q.RoleId);
這會不會有同樣的效果比在實體屬性使用Key
屬性?如果是這樣,爲什麼要在使用時使用modelBuilder
數據註釋更短且更易於讀取/寫入?是否有約定何時使用數據註釋或流利的API?
許多添加到一對多的關係:
modelBuilder.Entity<Role>()
.HasMany(q => q.Users)
.WithMany(q => q.Roles)
.Map(q => {
q.MapLeftKey("RoleId");
q.MapRightKey("UserId");
q.ToTable("UserRoles");
});
添加一對多的關係:
modelBuilder.Entity<UserEmail>()
.HasRequired(q => q.User)
.WithMany(q => q.UserEmails)
.HasForeignKey(q => q.EmailId);
是否需要將最後一行?