我首先使用EF模型创建两个实体
public class Brief
{
public int Id { get; set; }
public string Title { get; set; }
public string tId {get; set;}
public int SpeakerId { get; set; }
}
public class Speaker
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
我想做的是在Brief实体中将tId字段装饰为Unique。第二,当我按原样运行实体时,它会创建数据库,但不会在Briefs表中的SpeakerId和Speakers之间创建外键关系请告诉我如何1.将tId装饰得独一无二2.为什么不在SpeakerId和Speakers表上创建外键关系?感谢
对于问题2,您需要向实体添加一个导航属性:
public class Brief
{
public int Id { get; set; }
public string Title { get; set; }
public string tId {get; set;}
public int SpeakerId { get; set; }
//Navigational property
public virtual Speaker Speaker { get; set;} 1 Brief has 1 Speaker
}
根据关系,这也可以是Speaker entity:
公共虚拟Brief Brief{get;set;}的p ublic virtual ICollection<Speaker> Speakers { get; set;}
Vice Versa或n:m/1:m关系的ICollection
非键列上的唯一约束还不应基于http://entityframework.codeplex.com/workitem/299
进一步阅读/相关问题:
- 使用流利的API设置唯一约束
- http://bit.ly/OcE2HV
-
请先查看带有EF代码的唯一密钥根据EF版本的不同,可以在特性上设置属性。
-
使用导航属性,以便EF可以确定关系。注意,
virtual
关键字表示延迟加载。请参阅实体框架代码优先延迟加载