gpt4 book ai didi

c# - 实体类型 'Access' 需要定义一个主键。如果您打算使用无键实体类型调用 'HasNoKey()'

转载 作者:行者123 更新时间:2023-12-03 23:11:55 26 4
gpt4 key购买 nike

我有这个 ValueObject :

public class Access : ValueObject<Access>
{
public string ControllName { get; set; }
public string ActionName { get; set; }

private Access()
{

}
public Access(string controllerName, string actionName)
{
ControllName = controllerName;
ActionName = actionName;
}

protected override IEnumerable<object> GetEqualityComponents()
{
yield return ControllName;
yield return ActionName;
}
}

这是我的 ValueObject<Access> :
 public abstract class ValueObject<T>
where T : ValueObject<T>
{
protected abstract IEnumerable<object> GetEqualityComponents();

public override bool Equals(object obj)
{
var valueObject = obj as T;

if (ReferenceEquals(valueObject, null))
return false;

return IsEquals(valueObject);
}

private bool IsEquals(ValueObject<T> other)
{
return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());
}

public override int GetHashCode()
{
return GetEqualityComponents()
.Aggregate(1, (current, obj) => current * 23 + (obj?.GetHashCode() ?? 0));
}

public static bool operator ==(ValueObject<T> a, ValueObject<T> b)
{
if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
return true;

if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
return false;

return a.Equals(b);
}

public static bool operator !=(ValueObject<T> a, ValueObject<T> b)
{
return !(a == b);
}
}

这是我的 DBContext :
 public class StoreAdminPanelGetwayContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer(@"Server=.; initial catalog=StoreAdminPanelGetway;integrated security=true");

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(Role).Assembly);
}
public DbSet<Role> Roles { get; set; }
public DbSet<AccessLevel> AccessLevels { get; set; }

}

这是我的实体:
  public class AccessLevel : Entity
{
public int RoleId { get; set; }
public Access Access { get; set; }
public Role Role { get; set; }
}

但是当我需要时 add-migration initial数据库它告诉我这个错误:

The entity type 'Access' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.



但是 Access是值对象,它不能有 id 。我怎么解决这个问题 ???

最佳答案

EF Core 有 Owned Entity Types 的概念,可用于实现 DDD 值类型。

OnModelCreating你会做以下事情:

modelBuilder.Entity<AccessLevel>().OwnsOne(x => x.Access);

这将存储 AccessAccessLevel 位于同一数据库表中的对象对象,因此不需要主键。

关于c# - 实体类型 'Access' 需要定义一个主键。如果您打算使用无键实体类型调用 'HasNoKey()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60600835/

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