0

我有一个问题,我不知道最好的解决方案。希望有人在这里可以帮助=)流利的映射继承

我想解决的是: 我们必须在系统,个人和组织的用户类型。 我想要为这两个共享登录表(即用户可能不知道他们是哪种类型的用户,他们只是涉及到用户名和密码)。 所以我创建了一个用户名和密码的登录表。但是我需要知道登录人是谁,因此我需要提及任何人或组织。

考虑下面的类(简体):

public class Login 
{ 
    public string Username {get; set;} 
    public string Password {get;set;} 
} 

public class LoginPerson : Login 
{ 
    public Person Person {get;set;} 
} 

public class LoginOrg : Login 
{ 
    public Organization Organization {get;set;} 
} 

public class Person 
{ 
    public LoginPerson LoginPerson {get;set;} 
    //Lots of other properties. Removed for simplicity 
} 

public class Organization 
{ 
    public LoginOrg LoginOrg {get;set;} 
    //Lots of other properties. Removed for simplicity 
} 

的人员配置设置如下:

所有的
public class PersonConfiguration : EntityTypeConfiguration<Person> 
    { 
     public PersonConfiguration() 
     { 
      HasRequired(p => p.LoginPerson).WithRequiredPrincipal(p => p.Person); 
     } 
    } 

首先,这是行不通的。我收到一个异常说 “System.Data.EntityCommandCompilationException:System.Data.EntityCommandCompilationException:准备命令定义时发生错误。请参阅内部异常的详细信息---> System.Collections.Generic.KeyNotFoundException:给定的键没有出现在字典中..“ 所以我的第一个问题是为什么这不工作? 我的第二个问题是:哪种策略最适合这种继承? TPT,TPH还是TPC?

回答

0

我的例外的解决方案是设置正确的配置;-) PersonConfiguration不需要包含LoginPerson属性的任何配置。我添加了一个LoginPersonConfiguration - >

public class LoginPersonConfiguration : EntityTypeConfiguration<LoginPerson> 
{ 
    public LoginPersonConfiguration() 
    { 
     ToTable("LoginPerson"); 
     HasKey(l => l.Id); 
     HasRequired(l => l.Person).WithOptional(p => p.LoginPerson).Map(t => t.MapKey("PersonId")); 
    } 
} 

而且我也不得不登录添加到的DbContext类

public class MyDbContext : DbContext 
{ 
    public DbSet<Person> Persons { get; set; } 
    public DbSet<Login> Logins { get; set; } 
} 

当涉及到最合适的策略,我已经决定去TPT。

1

对于初学者来说,没有任何实体拥有密钥。你需要一个主键来使它们工作。 EF使用惯例来做到这一点,这是最后的类名加上Id,比如PersonId,或者你的关键是明确的,其属性为[Key]

其次,你的模型很混乱且相当循环。如果没有主键,则无法创建关联。

我很困惑为什么你有一个Person对象中的LoginPerson成员,并且对于一个组织来说是一样的?无论如何,你真的需要重新考虑这个模型并找出你的钥匙。

+0

对不起,不包括主键。当我简化课程时,我将它们移除了。所有的类都有一个Id列,这是一个PK。循环引用是有意的,因为它们是导航属性。但是,我解决了异常问题。而我的第二个问题可以通过google =回答) – Zaphod