I'm trying to setup a one to zero-or-one relationship, I thought I had it worked out, but I was wrong as I testing further. I clearly do not understand FluentAPI too well, but I also see that many have had the same or similar issue I am experiencing
Here are my Classes:
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 setup:
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: Name: Each property name in a type must be unique. Property name 'AccessLogID' is already defined.
I understand that AccessLogID
is a duplicate, but was hoping that I could leave it in my ErrorLog
model so I can reference it throughout the application (techincally, I am saving the Guid in a Session and logging Errors/Exceptions to it as needed, I am trying to avoid storing the entire Object, just the Guid).