我有一个简单的 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; }
}
我按照中所述建立了关系文档 https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities使用 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]
(但这是预料之中的,因为它是明确提到 https://learn.microsoft.com/en-us/ef/core/modeling/relational/default-values).
有一些关于如何处理常规实体的初始值的信息:
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
Edit:
本来我想新建一个SomeEntity
实例带有所有“嵌入”的预设属性SomeEntity.OwnedEntity
特性。
但是看看我关联的控制器是如何工作的,这一切都是有意义的......我有以下用于“创建”操作的方法:
[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());
}
那么这是正确的方法还是还有其他事情需要记住?