实体框架唯一字段问题

时间:2014-10-08 07:33:48

标签: c# .net entity-framework

我首先使用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和扬声器之间创建外部关键关系 请让我知道如何   1.装饰独特   2.为什么不在SpeakerId和Speakers表上创建外键关系? 谢谢

2 个答案:

答案 0 :(得分:0)

对于问题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
}  

根据关系,这也可以是ublic virtual ICollection<Speaker> Speakers { get; set;}公共虚拟简报的Speaker entity:副Versa {get; set;}`或n:m / 1:m relations

的ICollection

非关键列的唯一约束不应基于http://entityframework.codeplex.com/workitem/299

实现

进一步阅读/相关问题:

答案 1 :(得分:0)

  1. 请参阅Unique key with EF code first 根据EF版本,您可以在属性上设置属性。

  2. 使用导航属性,以便EF可以确定关系。 请注意,virtual关键字表示延迟加载。请参阅Entity Framework Code First Lazy Loading