我正在尝试建立一对一的关系,我以为我已经解决了,但是当我进一步测试时我错了。 我显然不太了解FluentAPI,但我也看到许多人遇到了与我相同或类似的问题
以下是我的课程:
public class BaseLogObject
{
public BaseLogObject()
{
Oid = Guid.NewGuid();
Date = DateTime.Now;
}
[Key]
[Column(Order = 0)]
public Guid Oid { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "Date")]
[Required]
[Column(Order = 1)]
public DateTime Date { get; set; }
}
public class AccessLog : BaseLogObject
{
public virtual ErrorLog ErrorLog { get; set; }
}
public class ErrorLog : BaseLogObject
{
//Hoping to keep this property, but .MapKey give "Unique" error
[Display(Name = "Access Log")]
public virtual Guid? AccessLogID { get; set; }
public virtual AccessLog AccessLog { get; set; }
}
FluentAPI 设置:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ErrorLog>()
.HasOptional(a => a.AccessLog)
.WithOptionalDependent(x => x.ErrorLog)
.Map(a => a.MapKey("AccessLogID"));
//Thought this worked, but AccessLogID became the PrimaryKey
//modelBuilder.Entity<ErrorLog>().HasKey(x => x.AccessLogID);
//modelBuilder.Entity<ErrorLog>().HasRequired(x => x.AccessLog);
//This creates a new column in SQL (AccessLog_Oid)
//modelBuilder.Entity<AccessLog>()
// .HasOptional(pi => pi.ErrorLog)
// .WithOptionalDependent(x => x.AccessLog);
//Tried reversing the relationship, no go
//modelBuilder.Entity<AccessLog>()
// .HasOptional(x => x.ErrorLog)
// .WithRequired(x => x.AccessLog);
base.OnModelCreating(modelBuilder);
}
AccessLogID:名称:类型中的每个属性名称必须是唯一的。属性名称"AccessLogID"已定义。
我知道AccessLogID
是重复的,但希望我可以将其保留在我的ErrorLog
模型中,以便我可以在整个应用程序中引用它(从技术上讲,我将 Guid 保存在会话中并根据需要记录错误/异常,我试图避免存储整个对象,只是 Guid(。
在这里问了很多次。这不是一个得到良好支持的关系。您必须共享主键,或按如下方式进行设置:
modelBuilder.Entity<ErrorLog>()
.HasOptional(e => e.AccessLog)
.WithMany()
.HasForeignKey(e => e.AccessLogID);
这里和这里类似。