gpt4 book ai didi

c# - 在 Entity Framework 中的抽象类上配置自动增量字段

转载 作者:太空狗 更新时间:2023-10-30 01:16:28 25 4
gpt4 key购买 nike

我有一些类似于这些的代码优先实体:

public abstract class Animal {
public int ID { get; set; }
public int NumberOfLegs { get; set; }
}

public class Dog : Animal {
public string OtherDogRelatedStuff { get; set; }
}

public class Bird : Animal {
public string OtherBirdRelatedStuff { get; set; }
}

public class MyContext : DbContext {

public IDbSet<Animal> Animals { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder) {

var pluraliser = PluralizationService.CreateService(new System.Globalization.CultureInfo("en-GB"));

modelBuilder.HasDefaultSchema("vs");
modelBuilder.Types().Configure(t => t.ToTable(pluraliser.Pluralize(t.ClrType.Name)));

// This next line doesn't give ID column IDENTITY(1,1)
modelBuilder.Entity<Animal>().Property(_ => _.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

// This line puts IDENTITY(1,1) on Animal.ID, but causes errors when I try to add/update data.
//modelBuilder.Entity<Dog>().Property(_ => _.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

base.OnModelCreating(modelBuilder);
}
}

我想要每种类型的表格...所以表格看起来像这样:

CREATE TABLE Animals (
ID INT NOT NULL IDENTITY(1,1),
NumberOfLegs INT NOT NULL,
CONSTRAINT pkAnimals PRIMARY KEY (ID)
)

CREATE TABLE Dogs (
ID INT NOT NULL,
OtherDogRelatedStuff VARCHAR(200),
CONSTRAINT pkDogs PRIMARY KEY (ID),
CONSTRAINT fkAnimal_Dog FOREIGN KEY (ID) REFERENCES Animals(ID)
)

CREATE TABLE Birds (
ID INT NOT NULL,
OtherBirdRelatedStuff VARCHAR(200),
CONSTRAINT pkBirds PRIMARY KEY (ID),
CONSTRAINT fkAnimal_Bird FOREIGN KEY (ID) REFERENCES Animals(ID)
)

数据看起来像这样:

---Animals----------
ID NumberOfLegs
1 4
2 4
3 2

---Dogs---------------------
ID OtherDogRelatedStuff
1 Woof1
2 Woof2

---Birds---------------------
ID OtherCatRelatedStuff
3 Sqwark1

但我无法使自动递增 ID 正常工作或正确配置。

我已经试过了:

modelBuilder.Entity<Animal>().Property(_ => _.ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

但是因为 Animal 是抽象的,所以这似乎没有在表上设置 IDENTITY(1,1) 属性。

我也尝试在 Dog 实体上做同样的事情,它正确地将标识属性添加到 Animals 表中的 ID 列,但我得到一个 UpdateException 当我尝试在 SaveChanges() 方法上向数据库添加新实体时:

A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'ID'.

如何正确设置抽象类型的ID列自动递增,并使其在添加数据时起作用?

最佳答案

我会说使用接口(interface)或单独的抽象类来放置像这样的通用功能:

public interface Common{
int ID { get; set; }
}
public class Animal : Common {
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public int NumberOfLegs { get; set; }
}

public class Dog : Common {
public int ID { get; set; }
public string OtherDogRelatedStuff { get; set; }
}

关于c# - 在 Entity Framework 中的抽象类上配置自动增量字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35067433/

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