复合键和IsRequired(false)

时间:2019-03-21 10:35:03

标签: c# linq entity-framework-core

如何告诉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,我用于检索数据的方法就可以正常工作。但这可能并非总是如此,我试图在这样的流畅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

1 个答案:

答案 0 :(得分:1)

只需删除

modelBuilder.Entity<ParentObject>().Property(mpo => mpo.CompositeKeyObj).IsRequired(false);

因为默认情况下,没有显式FK属性的FK关系为optional

但是,如果要显式配置,则应通过关系流畅的API(Property API仅用于非导航属性):

modelBuilder.Entity<ParentObject>()
    .HasOne(e => e.CompositeKeyObj)
    .WithMany()
    .IsRequired(false); // <--

最后,如果需要显式的FK属性,只需确保它们可为空即可-无需流畅的配置:

public class ParentObject
{
    // ...other properties    
    public int? CompositeKeyObjKey1 { get; set; }    
    public int? CompositeKeyObjKey2 { get; set; }    
    public CompositeKeyObject CompositeKeyObj { get; set; }    
}
相关问题