2015-02-09 59 views
1

我有两个代码拳头波苏斯(特派员和案例):定义一个对一个在EF代码首先用流利的API

public class Appointee 
{ 
    public int ID { get; set; } 
    public string ProfileID { get; set; } 
    public int? CaseID { get; set; } 
    public string FistName { get; set; } 
    public string LastName { get; set; } 
    public DateTime Dob { get; set; } 
    public string Ssn { get; set; } 
    public string GrantNumber { get; set; } 

    public virtual Case Case { get; set; } 
} 

public class Case 
{ 
    [Key] 
    public int CaseID { get; set; } 
    public string ProfileID { get; set; } 
    public int PSCStatusID { get; set; } 

    public virtual Appointee Appointee { get; set; } 
} 

在我们的术语特派员与档案的代名词。所以我们Appointtee的[Key]是ProfileID。

被任命者不必分配一个案例,所以我将CaseID设置为可为空的int - int ?.

从这我得到的错误,类似,EndPoint无法确定案例和被任命人之间。

我认为问题在案例中。 ProfileID是Appointtee的外键,应该是Virtual Appointtee Property的导航属性。 但我不认为它理解导航道具不是AppointeeID,而是ProfileID。

所以我把这个在的DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     base.OnModelCreating(modelBuilder); 
     modelBuilder.Entity<Appointee>().HasKey(a => a.ProfileID); 
     modelBuilder.Entity<Case>().HasKey(c => c.CaseID); 
     modelBuilder.Entity<Case>().HasRequired(c => c.Appointee); 
     modelBuilder.Entity<Appointee>().HasOptional(a => a.Case); 
    } 

现在,我得到:无效的列名称Appointee_ProfileID“。

如何正确设置它。

+0

我敢打赌,这将有助于:http://stackoverflow.com/questions/7055962/entity-framework-4-1-invalid-column-name – joelmdev 2015-02-10 01:10:14

回答

1

终于解决了这个问题。 这里有几件事。 我很习惯使用AutoInc设置代理主键,我为Appointee和Case设置了autoinc ID。

真的,被任命人的关键应该是ProfileID。

接下来,在实体框架中,从属表中的外键必须与父表中的主键相同,EF将其称为原则。

因此,一旦我在我的脑海中得知我的钥匙都是PK和FK,必须是ProfileID,我做了以下修复。

public class Appointee 
{ 
    [Key] 
    public string ProfileID { get; set; } 
    public string FistName { get; set; } 
    public string LastName { get; set; } 
    public DateTime Dob { get; set; } 
    public string Ssn { get; set; } 
    public string GrantNumber { get; set; } 

    public virtual Case Case { get; set; } 
} 

public class Case 
{ 
    [Key, ForeignKey("Appointee")] 
    public string ProfileID { get; set; } 
    public int PSCStatusID { get; set; } 

    [ForeignKey("ProfileID")] 
    public virtual Appointee Appointee { get; set; } 
} 

请注意Case中的[Key,ForeignKey(“Appointtee”)]属性,我需要告知EF,Appointtee是原则。