[英]How to configure zero or one to zero or one relationship with bi-directional navigation with 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 设置,但似乎都不起作用,例如:
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
添加尽可能多的记录,然后添加带有或不带有AccessLogID
ExceptionLog
记录。
希望这对其他人有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.