简体   繁体   中英

Multiplicity is not valid in Role in relationship: EF code first one to one relationship with same primary key and foreign key

I have two entities with one to one relationship where in target entity primary key and foreign key are same. Here is two entity and their fluent mapping.

public class Register
{ 
    public int Id { get; set; }
    public string Number { get; set; }
    // N.B: Here I can't have this virtual property for my project dependencies.
    //public virtual CustomerDisplay CustomerDisplay { get; set; }
}

public class CustomerDisplay
{
    public int RegisterId { get; set; }
    public double ReceiptViewPercent { get; set; }
    public virtual Register Register { get; set; }
}

public class RegisterConfiguration : EntityConfig<Register>
{
    public RegisterConfiguration(bool useIdentity, bool sqlServerCe)
        : base(sqlServerCe)
    {
        this.HasKey(t => t.Id);

        if (!useIdentity)
        {
            Property(d => d.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }

        this.Property(t => t.Number).IsRequired().HasMaxLength(20);      
    }
}

public class CustomerDisplayConfiguration: EntityConfig<CustomerDisplay>
{
    public CustomerDisplayConfiguration(bool sqlServerCe)
        : base(sqlServerCe)
    {
        this.HasKey(t => t.RegisterId);      
        this.HasRequired(t => t.Register).WithMany().HasForeignKey(d => d.RegisterId).WillCascadeOnDelete(false);
    }
}

I am getting following error:

在此输入图像描述

I have seen lots of related questions in stackoverflow but didn't find my solution. This one best match with my issue:

How to declare one to one relationship ...

Can anyone tell me how can I get rid of this issue. Thanks

Add again the CustomerDisplay navigation property:

public class Register
{ 
    public int Id { get; set; }
    public string Number { get; set; }

    public virtual CustomerDisplay CustomerDisplay { get; set; }
}

And configure the relationship as I show as follow:

 this.HasRequired(t => t.Register).WithOptional(r=>r.CustomerDisplay);

Notice that you didn't need to use HasForeignKey to specify that CustomerDisplay.CustomerId is the FK. This is because of Entity Framework's requirement that the primary key of the dependent be used as the foreign key. Since there is no choice, Code First will just infer this for you.

Update

If you can't add the CustomerDisplay navigation property into Register class, then I suggest you create an unidirectional one to one relationship. Use this configuration:

this.HasRequired(t => t.Register);

That is enough to tell EF who is the principal and who is the dependent entity in your relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM