I want to map one table to two unrelated entities: EntityBasic and EntityAdvanced. EntityAdvanced has extra business logic that I don't need for this one feature, and I would like to make a new Entity that only has fields from the table.
MyTable:
MyTableId : Guid
ParentId : Guid
Name : string
Description : string
Type : int
EntityBasic:
[Table("MyTable")]
public class EntityBasic
{
[Key]
public Guid MyTableId { get; set; }
public Guid ParentId { get; set }
public string Name { get; set; }
public string Description { get; set; }
public int Type { get; set; }
[ForeignKey("ParentId")]
public virtual List<EntityBasic> Entities{ get; set; }
}
EntityAdvanced:
[Table("MyTable")]
public class EntityAdvanced
{
private List<EntityAdvanced> _entities;
private List<Filter> _filters;
[Key]
public Guid MyTableId { get; set; }
public Guid ParentId { get; set }
public string Name { get; set; }
public string Description { get; set; }
public int Type { get; set; }
[ForeignKey("ParentId")]
public virtual List<EntityAdvanced> Entities
{
get { //Some complicated getter }
set { //Some complicated setter }
}
[NotMapped]
public string ImageUrl
{
get { //Some complicated getter }
set { //Some complicated setter }
}
public void SetFilters(//Some parameters)
{
//Some logic
}
}
When I do this i get this error:
The entity types 'EntityAdvanced' and 'EntityBasic' cannot share table 'MyTable' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.
Is there a way to do what I want?
As a base start, your EntityAdvanced
should inherit EntityBasic since they share the same base set of properties. You don't need to rewrite them. Note the extends EntityBasic
.
[Table("MyTable")]
public class EntityBasic
{
[Key]
public Guid MyTableId { get; set; }
public Guid ParentId { get; set }
public string Name { get; set; }
public string Description { get; set; }
public int Type { get; set; }
[ForeignKey("ParentId")]
public virtual List<EntityBasic> Entities{ get; set; }
}
[NotMapped]
public class EntityAdvanced : EntityBasic
{
//[NotMapped]
public string ImageUrl
{
get { //Some complicated getter }
set { //Some complicated setter }
}
public void SetFilters(//Some parameters)
{
//Some logic
}
}
Using inheritence, List<EntityBasic> Entities
could reference EntityAdvanced
objects so you don't need anymore to declare:
[ForeignKey("ParentId")]
public virtual List<EntityAdvanced> Entities
{
get { //Some complicated getter }
set { //Some complicated setter }
}
You can get usefull information about implementing inheritence with Entity Framework here .
Happy coding!
我认为您可以使用Entity Framework 6的“表拆分”功能,在此处查看示例: https : //www.c-sharpcorner.com/UploadFile/ff2f08/table-splitting-in-entity-framework- 6-代码优先的方法/
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.