我在SQL中有两个表用户和 UserDefaultModel 我有外键关联
<AssociationConnector Association="Ins_PricingDBModel.FK_UserDefaultModel_Users"
ManuallyRouted="false" />
我需要使用ModelBuilder实现相同的映射。这就是我试过的
modelBuilder.Entity<UserDefaultModel>()
.HasRequired(c=>c.User)
.WithMany()
.HasForeignKey(c => c.Id);
public class UserDefaultModel : Entity
{
public string DefaultModel { get; set; }
public virtual User User { get; set; }
}
但是我仍然无法映射值。语法是否有效?
答案 0 :(得分:0)
模型应如下所示:
public class User
{
public User()
{
}
public int UserId { get; set; }
public int UserDefaultModelId { get; set; }
public virtual UserDefaultModel UserDefaultModel { get; set; }
}
public class UserDefaultModel
{
public UserDefaultModel()
{
Users = new List<User>();
}
public int UserDefaultModelId { get; set; }
public virtual ICollection<User> Users { get; set; }
}
使用FLuent API进行一对多
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//one-to-many
modelBuilder.Entity<User>()
.HasRequired<UserDefaultModel>(s => s.UserDefaultModel) // User entity requires UserDefaultModel
.WithMany(u => u.Users); // UserDefaultModel entity includes many User entities
}