I have a class named MyEntity
public class MyEntity
{
public int Id { get; set; }
[Required]
[StringLength(300)]
public string Name { get; set; }
}
And an inherited class HubEntity
public class HubEntity : Entity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int EntityId { get; set; }
[Required]
[StringLength(300)]
public string RootName { get; set; }
}
This is based on existing tables in the database. There is one table for each class. Thus the EntityId
field in the HubEntity
table refers to the Id
field in the Entity
table.
In order to avoid demolishing the existing database, I run my code on a empty database and let the EF create the tables:
My concern is that the HubEntity table is built with both the Id and EntityId fields, the ID field being designed as the foreign key to the Entity table. I don't know how to get the EntityId field to be used as the foreign key.
I tried to tag it [ForeignKey("Entity")]
, but then I get an exception: the program looks for an Entity property in HubEntity that points to an Entity, which is not what I want because it's heritage.
I first created the application using DB first and here is what the model was looking like:
Thanks in advance for your help.
Cedric
OK, got it.
The class MyEntity is ok.
public class MyEntity
{
public int Id { get; set; }
[Required]
[StringLength(300)]
public string Name { get; set; }
}
The inherited class HubEntity must not contain the EntityId field:
public class HubEntity : Entity
{
[Required]
[StringLength(300)]
public string RootName { get; set; }
}
Now, in the MyModel.cs
, in OnModelCreating
, add the following clause:
modelBuilder.Entity<HubEntity>()
.Property(e => e.Id)
.HasColumnName("EntityId");
And the foreign key will be generated with the desired name. :)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments