System.InvalidOperationException:实体类型“myValueObjectClass”需要定义主键。IfYouIntendedTo 使用无密钥实体类型

System.InvalidOperationException: The entity type 'myValueObjectClass' requires a primary key to be defined.IfYouIntendedTo use a keyless entity type

提问人:MAHDI7 提问时间:11/14/2023 最后编辑:Svyatoslav DanylivMAHDI7 更新时间:11/14/2023 访问量:36

问:

我的项目是使用干净的架构创建的,当我想将记录插入到我的表中时,我收到此错误:Users

我的错误截图

我在域层中的实体类:User

using Movie_asp.ValueObjects;

namespace Movie_asp.Entities;

public class User
{
    public UserId Id { get; private set; }
    public UserFullName FullName { get; private set; }
    public Username Username { get; private set; }
    public Password Password { get; private set; }
    public Email Email { get; private set; }
    public CreatedAt CreatedAt { get; private set; }

    public User()
    {
    }

    public User(UserId id, UserFullName userFullName, Username username, Password password, Email email, CreatedAt createdAt)
    {
        Id = id;
        FullName = userFullName;
        Username = username;
        Password = password;
        Email = email;
        CreatedAt = createdAt;
    }
}

我的值对象类:

namespace Movie_asp.ValueObjects;

public record CreatedAt(DateTime Value);

我的班级DbContext

using Application.Data;
using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Movie_asp.Entities;
using Movie_asp.ValueObjects;

namespace Infrastructure;

public class ApplicationDbContext : DbContext, IApplicationDbContext, IUnitOfWork
{ 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(
            @"Server=localhost\SQLEXPRESS;Database=Test;Trusted_Connection=True;TrustServerCertificate=True;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasKey(i => i.Id);

        modelBuilder.Entity<User>()
            .Property(c => c.Id)
            .HasConversion(
                UserId => UserId.Value,
                value => new UserId(value)
                );
    }

    public DbSet<User> Users { get; set; }
}

似乎 Entity Framework Core 将我的值对象(类)视为实体。CreatedAt

如果您能帮助我解决这个问题,我将不胜感激。

ASP.NET 实体框架核心 域驱动设计 干净体系结构 值对象

评论

0赞 Svyatoslav Danyliv 11/14/2023
那么,在您看来,哪种数据库类型应该使用 EF Core?当然,它将其视为实体。正如您对属性所做的那样,您应该定义转换器并指定数据库类型。CreatedAtId

答: 暂无答案