EF Core 和 DDD 在数据库上具有复合键

问题描述 投票:0回答:1

我正在尝试为我的实体配置 EF Core,在数据库中我有一个如下表:

科鲁纳 蒂波
检验编号 int
问题组 varchar
问题 varchar
回答 varchar
观察 varchar
创建于 日期时间

我有一个复合主键,由

InspectionId, QuestionGroup, Question, Answer
组成。

我尝试像这样创建我的实体:

public class Checklist
{
    public Checklist(ChecklistId id, string observation, int userId, DateTime createdAt)
    {
        Id = id;
        CreatedAt = createdAt;
        Observation = observation;
        UserId = userId;
    }

    public ChecklistId Id { get; set; }
    public string Observation { get; set; }
    public int UserId { get; set; }
    public DateTime CreatedAt { get; set; }
}
public class ChecklistId
{
    public ChecklistId(int inspectionId, string questionGroup, string question, string answer)
    {
        InspectionId = inspectionId;
        QuestionGroup = questionGroup;
        Question = question;
        Answer = answer;
    }

    public int InspectionId { get; set; }
    public string QuestionGroup { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
}

如何配置 EF Core 以支持此实体?

我尝试使用此配置,但失败了:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Checklist>(entity =>
    {
        entity.HasKey(e => new { e.Id.InspectionId, e,Id.QuestionGroup, e.Id.Question, e.Id.Answer });

        entity.OwnsOne(e => e.Id, id =>
        {
            id.Property(i => i.InspectionId).HasColumnName("InspectionId");
            id.Property(i => i.QuestionGroup).HasColumnName("QuestionGroup");
            id.Property(i => i.Question).HasColumnName("Question");
            id.Property(i => i.Answer).HasColumnName("Answer");
        });

        // ... others properties
    });
}

项目是用

创建的
  • .NET 8
  • SQL Server 2008

我无法将数据库更改为具有像 Guid 这样的唯一 id 的表,是否可以使用域端的 id 配置具有复合键的 EF Core?

c# sql-server entity-framework-core domain-driven-design .net-8.0
1个回答
0
投票

只需将某个key涉及的所有属性直接放在实体类上即可:

public class Checklist
{

    public string Observation { get; set; }
    public int UserId { get; set; }
    public DateTime CreatedAt { get; set; }
    public int InspectionId { get; set; }
    public string QuestionGroup { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
}

和上下文配置:

entity.HasKey(e => new { e.InspectionId, e.QuestionGroup, e.Question, e.Answer });
© www.soinside.com 2019 - 2024. All rights reserved.