具有一对一或零关系的 FluentAPI

FluentAPI with One-to-one-or zero relationship

我似乎无法理解 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 设置,但 none 似乎有效,例如:

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."}

我相信它很简单,比如反转属性。感谢您的帮助!

我相信我已经想通了,采取与OP相同的类,可以应用以下FluentAPI:

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

这将允许我向 AccessLog 添加任意数量的记录,然后添加 ExceptionLog 条带或不带 AccessLogID 的记录。

希望这对其他人有帮助。