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?

4

2 回答 2

1

好吧,对于初学者来说,您的任何实体都没有密钥。您需要一个主键才能使它们工作。EF 使用约定来执行此操作,即类名加上末尾的 Id,如 PersonId,或者您的键是显式的,属性为[Key]

其次,您的模型令人困惑且相当循环。如果没有主键,就无法创建关联。

我很困惑为什么您在 Person 对象中有一个成员是 LoginPerson ,而对于组织也是如此?无论如何,你真的需要重新考虑这个模型并弄清楚你的钥匙是什么。

于 2013-08-29T18:05:55.633 回答
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。

于 2013-08-30T06:58:06.090 回答