【发布时间】:2021-12-15 17:59:28
【问题描述】:
这是一个关于可选拥有实体和外键的故事。
我正在使用 EF 5(代码优先),我这样做了:
public class Parent {
public Guid Id { get; private set; }
public OwnedType1? Owned1 { get; private set; }
public OwnedType2? Owned2 { get; private set; }
public Parent(Guid id, OwnedType1? owned1, OwnedType2? owned2) {
Id = id; Owned1 = owned1; Owned2 = owned2;
}
}
public class OwnedType1 {
public Guid? OptionalExternalId { get; private set; }
public OwnedType1 (Guid? optionalExternalId) {
OptionalExternalId = optionalExternalId;
}
}
public class OwnedType2 {
public Guid? OptionalExternalId { get; private set; }
public OwnedType2 (Guid? optionalExternalId) {
OptionalExternalId = optionalExternalId;
}
}
public class Shared {
public Guid Id { get; private set; }
public Shared (Guid id) {
Id = id;
}
}
现在,配置:
//-------- for Parent ------------
public void Configure(EntityTypeBuilder<Parent> builder) {
builder
.ToTable("Parents")
.HasKey(p => p.Id);
builder
.OwnsOne(p => p.Owned1)
.HasOne<Shared>()
.WithMany()
.HasForeignKey(x => x.OptionalExternalId);
builder
.OwnsOne(p => p.Owned2)
.HasOne<Shared>()
.WithMany()
.HasForeignKey(x => x.OptionalExternalId);
}
//-------- for OwnedType1 ------------
// (there's no builder as they're owned and EntityTypeBuilder<Parent> is enough)
//-------- for OwnedType2 ------------
// (there's no builder as they're owned and EntityTypeBuilder<Parent> is enough)
//-------- for Shared ---------------
public void Configure(EntityTypeBuilder<Shared> builder) {
builder
.ToTable("Shareds")
.HasKey(p => p.Id);
}
旁注:如果您想知道为什么 OwnedType1 和 OwnedType2 不都有一个名为“ParentId”的属性,那是因为它是由“OwnsOne”隐式创建的。
我的问题是这样的:
当我创建一个新的迁移时,OwnedType1 就像一个魅力,但对于 OwnedType2(这是准相同的),我得到了他的错误:
无法将属性“OptionalExternalId”添加到类型 'MyNameSpace.OwnedType2' 因为没有指定属性类型并且 没有对应的 CLR 属性或字段。添加阴影状态 属性,必须指定属性类型。
我不明白它在抱怨什么。 以及为什么它只为其中一个抱怨。
我知道您可能无法使用我的架构的这个简化版本来解决它,但我要问的是您认为它可能是什么(跟随您的 EF 大师的胆量):
- 缺少一些构造函数?
- 其中一个字段的可见性不正确?
- 导航定义错误?
- 错字?
- 一些棘手的事情(例如:如果您要拥有两个与 Shared 具有一对多关系的不同实体类,那么它们不能为外部键使用相同的名称。或者我需要使用复合键。或者诸如此类)。
【问题讨论】:
标签: c# entity-framework-migrations ef-core-5.0