提问人:MAHDI7 提问时间:11/14/2023 最后编辑:Svyatoslav DanylivMAHDI7 更新时间:11/14/2023 访问量:36
System.InvalidOperationException:实体类型“myValueObjectClass”需要定义主键。IfYouIntendedTo 使用无密钥实体类型
System.InvalidOperationException: The entity type 'myValueObjectClass' requires a primary key to be defined.IfYouIntendedTo use a keyless entity type
问:
我的项目是使用干净的架构创建的,当我想将记录插入到我的表中时,我收到此错误: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
如果您能帮助我解决这个问题,我将不胜感激。
答: 暂无答案
下一个:干净的架构和存储库
评论
CreatedAt
Id