【问题标题】:How to configure this model relationship using FLUENT API如何使用 FLUENT API 配置这种模型关系
【发布时间】:2019-06-24 08:48:06
【问题描述】:

用户(AskedUser)可以有许多其他用户(Asker)提出的问题。 用户(Asker)可以向其他用户(AskedUser)提问。 所以 QuestionModel 应该有外键来询问用户 id 和外键来询问问题的用户。

我是否按照我想要实现的目标构建模型?如何使用 fluent api 进行配置,因为仅使用数据注释无法实现这一点。

public class ApplicationUser : IdentityUser<long>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public DateTime BirthDate { get; set; }
    public ICollection<QuestionModel> AskedQuestions { get; set; }
}
public class QuestionModel
{
    public int Id { get; set; }
    public string Content { get; set; }
    public bool IsAnswered { get; set; }
    public long AskerId { get; set; }
    public ApplicationUser Asker { get; set; }
    public long AskedUserId { get; set; }
    public ApplicationUser AskedUser { get; set; }
}

这是我迄今为止尝试过的

 builder.Entity<ApplicationUser>()
           .HasMany(user => user.AskedQuestions)
           .WithOne(q => q.AskedUser)
           .HasForeignKey(user => user.AskedUserId)
           .HasConstraintName("ForeignKey_User_AskedQuestion")
           .HasForeignKey(user => user.AskerId)
           .HasConstraintName("ForeignKey_Asker_QuestionAsked")
           .IsRequired(true);

【问题讨论】:

  • 您的代码不起作用吗?有错误吗?

标签: c# asp.net entity-framework-core ef-fluent-api


【解决方案1】:

您可以在 QuestionModel 上进行操作

//Asker relation
builder.Entity<QuestionModel>()
           .HasOne(q=> q.Asker)
           .Withmany(u => u.AskedQuestions)
           .HasForeignKey(q=> q.AskerId)
           .HasConstraintName("ForeignKey_Asker_QuestionAsked")
           .IsRequired(true);

//Asked relation
builder.Entity<QuestionModel>()
           .HasOne(q=> q.AskedUser)
           .Withmany()
           .HasForeignKey(q=> q.AskeduserId)
           .HasConstraintName("ForeignKey_User_AskedQuestion")
           .IsRequired(true);

我在依赖模型而不是根元素上使用 Fluent API。

【讨论】:

    猜你喜欢
    • 2020-11-06
    • 2015-07-27
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2019-04-06
    相关资源
    最近更新 更多