问题描述
我有两个课程:客户和调查。
I have 2 classes: Client and Survey.
每个客户都可以进行许多调查,但只能进行一次默认调查。
Each Client can have many surveys - but only one default survey.
我已经定义了这样的类:
I have defined the classes like this:
public class Client
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string ClientName { get; set; }
public Nullable<int> DefaultSurveyID { get; set; }
[ForeignKey("DefaultSurveyID")]
public virtual Survey DefaultSurvey { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public class Survey
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string SurveyName { get; set; }
[Required]
public int ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual Client Client { get; set; }
}
根据我的预期创建客户端表:
This creates the Client table as I expect:
[dbo].[Clients]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[ClientName] [nvarchar](max) NULL,
[DefaultSurveyID] [int] NULL
)
但调查表有一个额外的外键:
But the Survey table has an extra foreign key:
[dbo].[Surveys]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[SurveyName] [nvarchar](max) NULL,
[ClientID] [int] NOT NULL,
[Client_ID] [int] NULL
)
为什么是代码首先产生这种关系,如何告诉它不要?
Why is Code First generating this relationship and how to I tell it not to?
推荐答案
问题是当两个实体之间有多个关系时,EF Code First不能找出匹配哪个导航属性,除非你告诉它如何,这里是代码:
The problem is that when you have multiple relationships between two entities, EF Code First isn't able to find out which navigation properties match up, unless, you tell it how, here is the code:
public class Client
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string ClientName { get; set; }
/****Change Nullable<int> by int?, looks better****/
public int? DefaultSurveyID { get; set; }
/****You need to add this attribute****/
[InverseProperty("ID")]
[ForeignKey("DefaultSurveyID")]
public virtual Survey DefaultSurvey { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
对于您以前的版本,EF正在创建额外的关系,因为它没有'不知道 DefaultSurvey
属性是否引用调查$ c $的
ID
c> class,但可以让它知道,添加属性 InverseProperty
其参数是调查$ c $中的属性名称c>你需要
DefaultSurvey
来匹配。
With your previous version, EF was creating that extra relationship because it didn't know that the DefaultSurvey
property was referencing the ID
of the Survey
class, but you can let it know that, adding the attribute InverseProperty
whose parameter is the name of the property in Survey
you need DefaultSurvey
to match with.
这篇关于实体框架代码首先:如何为“默认值”注释外键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!