创建实体模型多对多 CodeFirst Ef6
Posted
技术标签:
【中文标题】创建实体模型多对多 CodeFirst Ef6【英文标题】:Create entity model Many-To-Many CodeFirst Ef6 【发布时间】:2021-12-06 07:35:07 【问题描述】:我希望 Db 使用 Code-First
我做了什么:
public class Responses
public int UserId get; set;
public virtual AppUser AppUser get; set;
public int QuestionId get; set;
public virtual Question Question get; set;
public string Answer get; set;
public class Question
public int idQuestion get; set;
public string TextQuestion get; set;
public ICollection<Responses> Responses get; set;
public class AppUser : IdentityUser<int, AppUserLogin, AppUserRole, IdentityUserClaimBase>, ICRMRepository, IEditableEntity, IEntityBase
public int idUser get;set;
public ICollection<Responses> Responses get; set;
接下来我去 DbContext:
modelBuilder.Entity<Responses>()
.HasKey(x => new x.UserId, x.QuestionId);
modelBuilder.Entity<Responses>()
.HasOne(x=>x.User)
无法解析符号“HasOne”
如果我想得到这样的 db,我该怎么办?
如何配置我与 fluent API 的关联?或者有没有更好的方法来创建关联表?
UPD
【问题讨论】:
【参考方案1】:更改响应类,将 AppUser 属性替换为 User
public class Responses
public int UserId get; set;
public virtual AppUser User get; set;
........
并将此代码用于 Db 上下文
modelBuilder.Entity<Response>(entity =>
entity.HasOne(d => User)
.WithMany(p => p.Responses)
.HasForeignKey(d => d.UserId);
entity.HasOne(d => d.Question)
.WithMany(p => p.Responses)
.HasForeignKey(d => d.QuestionId;
);
【讨论】:
这很有效。我收到问题“类名用户无效” @Boris 这只是一个错字。你可以修复它 我明白了。修复它并粘贴我的类型而不是“用户”我粘贴 AppUser @Boris 现在工作了吗 我更新了我的问题,见图【参考方案2】:我可以解决它:
public class AppUser : IdentityUser<int, AppUserLogin, AppUserRole, IdentityUserClaimBase>, ICRMRepository, IEditableEntity, IEntityBase
public ICollection<Response> Responses get; set;
public class Question
public int Id get; set;
public string TextQuestion get; set;
public ICollection<Response> Responses get; set;
public class Response
public int Id get; set;
***public int AppUserId get; set; ***
public int QuestionId get; set;
public virtual AppUser AppUser get; set;
public virtual Question Question get; set;
public string Answer get; set;
数据库上下文:
public DbSet<Question> Questions get; set;
public DbSet<Response> Responses get; set;
EF6 明白我想要什么
【讨论】:
以上是关于创建实体模型多对多 CodeFirst Ef6的主要内容,如果未能解决你的问题,请参考以下文章
EF CodeFirst系列---配置1对1,1对多,多对多关系