Derek
Derek

Reputation: 682

FluentAPI with One-to-one-or zero relationship

I can't seem to understand FluentAPI, I really need to educate myself, but I am hoping to get a head start on this one.

I have two objects, AccessLog, this will have an optional ExceptionLog object, and ExceptionLog will have an optional AccessLog.

I believe this is call 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; }

}

I tried a few FluentAPI setups, but none seem to work, for example:

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);

This setup produces the following error, but I don't know where to go from here:

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

I believe it is something simple like reversed properties. Thank you for the help!

Upvotes: 1

Views: 86

Answers (1)

Derek
Derek

Reputation: 682

I believe I have figured it out, taking the same Classes as the OP, can apply the following FluentAPI:

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

This will allow me to add as many records to the AccessLog as I like, then add ExceptionLog records with or without an AccessLogID.

Hope this helps others.

Upvotes: 1

Related Questions