FluentAPI,具有一对一或零关系

时间:2018-02-24 03:24:07

标签: c# entity-framework one-to-one ef-fluent-api

我似乎无法理解FluentAPI,我真的需要自学,但我希望能够在这一点上先行一步。

我有两个对象AccessLog,这将有一个可选的ExceptionLog对象,而ExceptionLog将有一个可选的AccessLog

我相信这是致电one to one or zero

public class AccessLog : BaseLogObject
{
    //...other properties

    public virtual ExceptionLog ExceptionLog { get; set; }
}


public class ExceptionLog : BaseLogObject
{
    //...other properties

    [Display(Name = "Access Log")]
    public Guid? AccessLogID { get; set; }

    public virtual AccessLog AccessLog { get; set; }
}

//BaseLogObject (contains the Key for each object)
public class BaseLogObject
{
    public BaseLogObject()
    {
        Oid = Guid.NewGuid();
    }

    [Key]
    [Column(Order = 0)]
    public Guid Oid { get; set; }

}

我尝试了一些FluentAPI设置,但似乎都没有,例如:

modelBuilder.Entity<ExceptionLog>()
    .HasOptional(x => x.AccessLog)
    .WithOptionalDependent(x => x.ExceptionLog);

modelBuilder.Entity<AccessLog>()
    .HasOptional(x => x.ExceptionLog)
    .WithOptionalDependent(x => x.AccessLog);

modelBuilder.Entity<ExceptionLog>()
  .HasKey(x => x.AccessLogID);

此设置产生以下错误,但我不知道从何处开始:

{"The navigation property 'AccessLog' declared on type 
'x.Entities.Logs.ExceptionLog' has been configured with conflicting foreign keys."}

我认为它像反向属性一样简单。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

我相信我已经弄清楚了,使用与OP相同的类,可以应用以下FluentAPI:

modelBuilder.Entity<ExceptionLog>()
    .HasOptional(x => x.AccessLog)
    .WithOptionalDependent(x => x.ExceptionLog)
    //.WithOptionalPrincipal(x => x.ExceptionLog)
    ;

这样我就可以根据需要向AccessLog添加任意数量的记录,然后添加ExceptionLog条记录,无论是否有AccessLogID

希望这有助于其他人。