在 .NET 6 中,Entity Framework Core (EF Core) 默认禁用了将主键和非主键的属性进行联合的功能。这是为了确保数据一致性和避免潜在的问题。

如果你想要使用联合主键和非主键的属性,可以采取以下步骤来解决这个问题:

  1. 在你的实体类中,使用HasKey()方法将属性设置为联合主键。例如:
public class MyEntity
{
    public int Key1 { get; set; } 
    public int Key2 { get; set; } 
    public string NonKeyProperty { get; set; } 

    protected bool Equals(MyEntity other)
    {
        return Key1 == other.Key1 && Key2 == other.Key2 && NonKeyProperty == other.NonKeyProperty;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((MyEntity) obj);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Key1, Key2, NonKeyProperty);
    }
}
  1. 在你的DbContext类中,使用HasAlternateKey()方法将非主键属性设置为备用键。例如:
public class MyDbContext : DbContext
{
    public DbSet<MyEntity> Entities { get; set; } 

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntity>()
            .HasKey(e => new { e.Key1, e.Key2 });
        
        modelBuilder.Entity<MyEntity>()
            .HasAlternateKey(e => e.NonKeyProperty);
    }
}

通过以上步骤,你就可以在 .NET 6 EF Core 中使用联合主键和非主键的属性了。

.NET 6 EF Core 联合主键和非主键属性报错解决方法

原文地址: https://www.cveoy.top/t/topic/fd6c 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录