繁体   English   中英

如何在实体框架核心中使用泛型类型?

[英]How can I use a generic type with entity framework core?

如果我有一个看起来像这样的域模型:

public class Foo<T> {
    public Guid Id { get; set; }
    public string Statement { get; set; }
    public T Value { get; set; }
}

我想将它用于内置数据类型(字符串、整数等...)以及日期。 我想像这样使用它:

var foo = new Foo<string>();
foo.Value = "Hey";

如何使用 EF Core 将其保存到数据库中?

我想数据库表看起来像

| Id | Statement | ValueAsString | ValueAsDecimal | ValueAsDate | ValueAsInt | 
| 1  | NULL      | "Hey"         |                |             |            |
| 2  | NULL      |               | 1.1            |             |            |

你应该还有一堂课。 你的类Foo应该是抽象的。 所以你会得到“:

public abstract class Foo<T> {
    public Guid Id { get; set; }
    public string Statement { get; set; }
    public T Value { get; set; }
}

那么你的实现类将是:

public class Orders: Foo<Order> {
}

现在您拥有了可以存储的具有泛型类型的Orders类。

如果您想将不同的值类型持久保存到数据库中类似于您问题中的表的单个表中,您可以这样做:

public interface IHasValue<T> {
    T Value { get; set; }
}

public abstract class Foo {
    public Guid Id { get; set; }
    public string Statement { get; set; }
}

public class Foostring : Foo, IHasValue<string> {
    string Value { get; set; }
}

public class FooInt : Foo, IHasValue<int> {
    int Value { get; set; }
}

在您的DbContext类中添加属性:

public DbSet<FooString> FooStrings { get; set: }
public DbSet<FooInt> FooInts { get; set; }

您可以在表中设置的列名OnModelCreating你的方法DbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // include the base class so a single table is created for the hierarchy
    // rather than a table for each child class
    modelBuilder.Entity<Foo>().ToTable("Foos");

    // Specify the column names or you will get weird names
    modelBuilder.Entity<FooString>().Property(entity => entity.Value)
        .HasColumnName("ValueAsString");
    modelBuilder.Entity<FooInt>().Property(entity => entity.Value)
        .HasColumnName("ValueAsInt");
}

此代码将生成一个表Foos其中包含IdStatementDiscriminatorValueAsStringValueAsInt 可以在此处找到有关Discrimiator列的更多信息

结果表的图像

您仍然需要为要用于T每个类型/列创建一个类,我认为您无法解决这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM