gpt4 book ai didi

c# - Entity Framework 核心 : How to configure model with two One to Many relations in one entity referencing the same table

转载 作者:太空宇宙 更新时间:2023-11-03 12:43:54 25 4
gpt4 key购买 nike

我想跟踪谁创建了一个实体,谁编辑了(最后)该实体。因为我想为项目中的每个实体执行此操作,所以我在名为 EntityBase 的基类中执行此操作。

如果我使用相应的 ForeignKey 属性在 EntityBase 类中取消注释 EditorUser,则 Context.Database.EnsureCreated 方法会抛出以下异常:

无效操作异常:附加信息:无法确定在“User.CreatorUser”和“User”之间检测到的一对一关系的子/依赖方。要识别关系的子/依赖方,请配置外键属性。

谁能帮我配置模型来完成我的要求?

public class EntityBase
{
public Guid Id { get; set; }
public Guid CreatorUserId { get; set; }
[ForeignKey(nameof(CreatorUserId))]
public User CreatorUser { get; set; }
public Guid? EditorUserId { get; set; }
//[ForeignKey(nameof(EditorUserId))]
//public User EditorUser { get; set; }
}
public class User : EntityBase
{
public String Name { get; set; }
}
public class House : EntityBase
{
public String Address { get; set; }
}
class Context : DbContext
{
public Guid CurrentUserId = new Guid("3de85c1f-3ce1-4342-a582-83d6cc8e308f");

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

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(@"Data Source = c:\Temp\eftest.db;");
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
base.OnModelCreating(modelBuilder);
}

public override int SaveChanges()
{
var changeSet = ChangeTracker.Entries<EntityBase>();
if (changeSet != null)
{
foreach (var entry in changeSet.Where(c => c.State != EntityState.Unchanged))
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatorUserId = CurrentUserId;
break;
default:
entry.Entity.EditorUserId = CurrentUserId;
break;
}
}
}
return base.SaveChanges();
}
}

最佳答案

嗯,基本上 EntityBase 中的 CreatorUser 派生自 User,它使用 EntityBase 作为基础。所以这是一个先有鸡还是先有蛋的问题。您可以为 Parent 创建另一个用户实体并将其添加到 EntityBase 中。

关于c# - Entity Framework 核心 : How to configure model with two One to Many relations in one entity referencing the same table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38010220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com