David J.E.
David J.E.

Reputation: 368

How can I set a foreign key as primary key with Entity Framework?

I'm trying to set a foreign key as primary key using Entity Framework and fluent api.

modelBuilder.Entity<Z>()
            .HasRequired(m => m.X)
            .WithRequireDependent(m => m.Y)
            .WillCascadeOnDelete();

My class:

public class Z
{
        [Key,ForeignKey("X")]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public RentCar X { get; set; }
        public DateTime AIA_KM { get; set; }
        public DateTime AIA_FEC { get; set; }
}

I checked this StackoverFlow question Entity Framework Foreign Key as Primary Key Code First before but doesn't work for me.

Thank you.

Upvotes: 2

Views: 4660

Answers (1)

ocuenca
ocuenca

Reputation: 39386

Add the PK of RentCar in your Z entity and add the following config:

public class Z
{
        public int RentCarId { get; set; }//Add this

        public RentCar X { get; set; }
        public DateTime AIA_KM { get; set; }
        public DateTime AIA_FEC { get; set; }
}

And add this configuration:

modelBuilder.Entity<Z>().HasKey(t => t.RentCarId );// Add this
modelBuilder.Entity<Z>()
            .HasRequired(m => m.X)
            .WithRequireDependent(m => m.Y)
            .WillCascadeOnDelete();

From this link:

Selecting WithRequiredPrincipal will make the entity that you are configuring the principal, meaning it contains the primary key of the relationship. Selecting WithRequiredDependent will make the entity that you are configuring the dependent, meaning it will have the foreign key of the relationship.

So by convention the PK of you dependent entity (Z) is going to be the FK of the one to one relationship

Upvotes: 2

Related Questions