gpt4 book ai didi

c# - 在 EF Core 中设置属性约定?

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

在 NHibernate 中,他们有一个约定俗成的小概念,您可以说,如果一个实体有一个 Name 属性,并且它是一个字符串,您可以对其应用某些数据库行为(例如,将其设置为非空,最大长度 x,如果您可以确定所有名称都是唯一的,则可能是唯一的。

这将是一个小类,您可以将它添加到您的实例工厂,然后砰!数据库模型将相应地构建。

EF Core 中有类似的机制吗?我似乎找不到任何东西,而且每个属性的每个实体的流畅配置数量多得可笑,非常乏味。

最佳答案

在 EF Core 中,内置约定用于创建初始模型,您可以在 OnModelCreating 中覆盖或修改该模型。

您可以简单地遍历您的实体和属性覆盖约定。这足以代替来自 EF6 的自定义约定(至少到目前为止)自定义约定还没有摆脱积压。参见 https://github.com/aspnet/EntityFrameworkCore/issues/214状态和一些例子。在 OnModelCreating 中读取自定义属性以驱动(或覆盖)您的实体配置也是一种非常常见的模式。

所以你的例子:

if an entity had a Name property, and it was a string, you could apply certain db behavior to it (for example, set it to not null, max length x, maybe unique if you could be certain all names would be unique).

会是这样的:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var props = from e in modelBuilder.Model.GetEntityTypes()
from p in e.GetProperties()
where p.Name == "Name"
&& p.PropertyInfo.PropertyType == typeof(string)
select p;

foreach (var p in props)
{
p.SetMaxLength(200);
p.IsNullable = false;
p.DeclaringEntityType.AddKey(p);
}

base.OnModelCreating(modelBuilder);
}

或者,如果您想强制所有 DataTime 列的数据类型,例如:

    var dateProps = from e in modelBuilder.Model.GetEntityTypes()
from p in e.GetProperties()
where p.PropertyInfo.PropertyType == typeof(DateTime)
select p;
foreach (var prop in dateProps)
{
prop.Relational().ColumnType = "datetime2(4)";

}

关于c# - 在 EF Core 中设置属性约定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52629412/

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