2013-05-18 82 views
0
public class Slider_Locale 
    { 
     [Key] 
     public int Slider_LocaleID { get; set; } 

     [ForeignKey("Culture")] 
     public int CultureID { get; set; } 
     public string Slogan { get; set; } 


     public virtual Culture Culture { get; set; } 
    } 

    public class Culture 
    { 
     [Key] 
     public int CultureID { get; set; } 
     public string CultureName { get; set; } 
     public string DisplayName { get; set; } 

     public virtual Slider_Locale slider_Locale { get; set; } 
    } 

它给错误如下:实体关系

System.Data.Edm.EdmAssociationEnd:模型生成过程中检测到

一个或多个验证错误:多重无效角色 'Slider_Locale_Culture_Source'的关系为 'Slider_Locale_Culture'。因为依赖角色属性不是 的关键属性,所以依赖角色的多重性的上限必须是* * *。

我怎么能设计这种关系?请帮助我,因为我是mvc和实体的新手。

回答

0

这是一个有点棘手的事情,首先围绕你的大脑。问题在于你试图建立一个1:1(或1:0)的映射,但是你的模型中没有任何东西来执行这种映射。例如,如果有多个Slider_Locale对象具有相同的CultureID值,该怎么办?您的应用程序将如何知道选择哪一个?

现在,您可能知道这绝不会发生,但实体框架不会发生,并且它必须谨慎,因此它不会让您建立它不能建立的关系证明与表结构一致。理想情况下,它会让你指定除主键以外的唯一约束来解决这个问题,也许有一天它会,但现在最简单的方法是将它改为一对多映射。例如,你可以这样做:

public class Slider_Locale 
{ 
    [Key] 
    public int Slider_LocaleID { get; set; } 

    [ForeignKey("Culture")] 
    public int CultureID { get; set; } 
    public string Slogan { get; set; } 

    public virtual Culture Culture { get; set; } 
} 

public class Culture 
{ 
    [Key] 
    public int CultureID { get; set; } 
    public string CultureName { get; set; } 
    public string DisplayName { get; set; } 

    // Note that this got changed to ICollection<> 
    public virtual ICollection<Slider_Locale> slider_Locales { get; set; } 
} 

你可以做的另一件事是改变类,以便它们共享相同的主键值,但为了做到这一点,你将不得不作出的至少一个关系可选。如果你让我知道Slider_Locale.Culture是否为空,或者是Culture.slider_Locale,或者两者都可以,我可以举一个例子。