Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF7 - Custom column name for HasOne relationship

How do you specify a custom column name with a HasOne relationship in EF7?

Consider the following sample classes:

public class House
{
    public int Id { get; set; }
    public int BedroomCount { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public int Id { get; set; }
    public string StreetName { get; set; }
    public string StreetNumber { get; set; }
}

And this fluent configuration:

modelBuilder.Entity<House>()
    .HasOne(x => x.Address)
    .WithOne()
    .OnDelete(DeleteBehavior.Cascade);

Which leads to this DB configuration:

CREATE TABLE [House] (
[Id] int NOT NULL IDENTITY,
[AddressId] int,
[BedroomCount] int NOT NULL,
CONSTRAINT [PK_House] PRIMARY KEY ([Id]),
CONSTRAINT [FK_House_Address_AddressId] FOREIGN KEY ([AddressId]) REFERENCES [Address] ([Id]) ON DELETE CASCADE);

CREATE TABLE [Address] (
[Id] int NOT NULL IDENTITY,
[StreetName] nvarchar(max),
[StreetNumber] nvarchar(max),
CONSTRAINT [PK_Address] PRIMARY KEY ([Id]));

How do I specify a column name other than "AddressId" on the House table? I cannot find a method similar to HasColumnName like there is on non-navigation properties.

I'm using Entity Framework 7 RC1-Final.

like image 283
SkipHarris Avatar asked Oct 31 '22 11:10

SkipHarris


1 Answers

You can use Data Annotations to configure the foreign key of your relationship.

public int AddressID { get; set; }

[ForeignKey("AddressID")]
public Address Address { get; set; }

This requires a property that will be used as the foreign key in your relationship. Also, note that it is recommended that you have a explicit foreign key for your relationships other than a shadow foreign key. This will prevent you to have a lot of problems when inserting/updating since you don't need to set the entire navigation property Address to save a House entity. See the problem here

Not tested but perhaps this could work (can't find a way to install EF7 right now)

modelBuilder.Entity<House>()
    .HasOne(x => x.Address)
    .WithOne()
    .OnDelete(DeleteBehavior.Cascade);
    .HasForeignKey(x => x.AddressID);

You can check here for more examples: Foreign Key Relationships EF7

like image 195
jpgrassi Avatar answered Nov 16 '22 10:11

jpgrassi