如果不需要一个由复合键连接的对象,如何告诉EF Core?
我的设置如下(简化):
public class ParentObject
{
public int Key1 { get; set; }
public int Key2 { get; set; }
public CompositeKeyObject CompositeKeyObj { get; set; }
// ...other properties
}
public class CompositeKeyObject
{
public int Key1 { get; set; }
public int Key2 { get; set; }
public int? ChildObjectId { get; set; }
public ChildObject ChildObj { get; set; }
}
public class ChildObject
{
public int ChildObjectId { get; set; }
// ... other properties
}只要ParentObject有一个匹配的CompositeObject,我检索数据的方法就能正常工作。但情况可能并不总是这样,我试图在fluent API中这样做:
modelbuilder.Entity<CompositeKeyObject).HasKey(p => new { p.Key1, p.Key2 }
modelBuilder.Entity<ParentObject>().Property(mpo => mpo.CompositeKeyObj).IsRequired(false);但如果我这样做,我会犯一个错误:
ParentObject.CompositeKeyObj‘是'CompositeKeyObject’类型,当前数据库提供程序不支持它。要么更改属性CLR类型,要么使用'NotMapped‘属性忽略该属性,或者在'OnModelCreating’中使用'EntityTypeBuilder.Ignore‘。
我怎么知道,并不总是有一个匹配的CompositeKeyObject
发布于 2019-03-21 12:04:30
只要移除
modelBuilder.Entity<ParentObject>().Property(mpo => mpo.CompositeKeyObj).IsRequired(false);因为在默认情况下,FK关系w/o显式FK属性是可选。
但是,如果您想显式地配置它,它应该是通过关系fluent API ( Property API仅用于非导航属性):
modelBuilder.Entity<ParentObject>()
.HasOne(e => e.CompositeKeyObj)
.WithMany()
.IsRequired(false); // <--最后,如果您需要显式的FK属性,只需确保它们是可空的--不需要fluent配置:
public class ParentObject
{
// ...other properties
public int? CompositeKeyObjKey1 { get; set; }
public int? CompositeKeyObjKey2 { get; set; }
public CompositeKeyObject CompositeKeyObj { get; set; }
}https://stackoverflow.com/questions/55278482
复制相似问题