gpt4 book ai didi

asp.net - 如何在 Entity Framework Core 2.0 中为拥有的实体类型指定默认属性值?

转载 作者:行者123 更新时间:2023-12-04 02:59:14 27 4
gpt4 key购买 nike

我有一个简单的 POCO 类型,比如说

public class OwnedEntity {

public string stringProperty { get; set; }
public decimal decimalProperty { get; set; }
public bool boolProperty { get; set; }
public int intProperty { get; set; }
}

和一个带有 OwnedEntity 的实际实体引用

public class SomeEntity {

public string Id { get; set; }
public OwnedEntity OwnedEntity { get; set; }
}

我按照 documentation 中的描述建立关系使用 EF Core 的 Fluent API:

protected override void OnModelCreating (ModelBuilder builder) {

base.OnModelCreating (builder);

builder.Entity<SomeEntity> ().OwnsOne (e => e.OwnedEntity);
}

我找不到关于如何为 OwnedEntity 的所有属性定义默认值的任何信息.我尝试像这样初始化属性:

public class OwnedEntity {

public string stringProperty { get; set; } = "initial"
public decimal decimalProperty { get; set; } = -1M;
public bool boolProperty { get; set; } = false;
public int intProperty { get; set; } = -1;
}

但没有效果。同样适用于 [DefaultValueAttribute] (但这是意料之中的,因为它是 explicitly mentioned )。

有一些关于如何处理常规实体初始值的信息:

modelBuilder.Entity<SomeOtherEntity>()
.Property(e => e.SomeIntProperty)
.HasDefaultValue(3);

但是由于我面对的是一个拥有的实体类型,我无法通过 Entity<T> 访问该类型.

有没有办法做我正在寻找的事情?

一些值得一提的事情:

  • 我有大量的特定实体,其中大多数都使用 OwnsOne关系
  • 声明所有OwnedEntity -基类中的属性不是一个选项,因为并非所有实体都具有这些属性
  • 我正在使用 EF Core 2.0.3 和 ASP.NET Core MVC 2.0.4

编辑:

本来我想新创建SomeEntity实例带有所有“嵌入式”的预设属性 SomeEntity.OwnedEntity属性。

但是看看我关联的 Controller 是如何工作的,这一切都是有道理的......我有以下“创建”操作的方法:

[HttpGet]
public IActionResult Create () {
return View (nameof (Create));
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create (SomeEntity model) {
context.Add (model);
await context.SaveChangesAsync ();

// redirect etc.
}

这意味着没有为 [HttGet] 创建对象过载 Create并且所有链接到属性的 HTML 输入(通过 asp-for )最初都是空的。好的。所以我想这样做的正确方法是手动创建一个新实例 SomeEntity并将其传递给 Create像这样看:

[HttpGet]
public IActionResult Create () {
return View (nameof (Create), new SomeEntity());
}

那么这是正确的方法吗?还是还有其他一些事情需要牢记?

最佳答案

假设您了解什么是 EF Core Default Values是为了,只是在寻找相当于 Entity<T>().Property(...) 的东西相等的。

始终使用 ReferenceOwnershipBuilder<TEntity,TRelatedEntity> 为每个所有者类型配置拥有的实体类方法。要访问此类,您可以使用 OwnsOne 的结果方法,或使用 OwnsOne Action<ReferenceOwnershipBuilder<TEntity,TRelatedEntity>> 类型的第二个参数重载.

例如,使用第二种方法:

builder.Entity<SomeEntity>().OwnsOne(e => e.OwnedEntity, ob =>
{
ob.Property(e => e.stringProperty)
.HasDefaultValue("initial");
ob.Property(e => e.decimalProperty)
.HasDefaultValue(-1M);
// etc.
});

关于asp.net - 如何在 Entity Framework Core 2.0 中为拥有的实体类型指定默认属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50803797/

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