0

I am using EF Model first to create two entities

 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; }
    }

What I want to do is in Brief entity decorate tId field as Unique. Second when I run entities as it is, it creates the database but it does not create foreigh key relation between SpeakerId in Briefs table and Speakers Please let me know how 1. Decorate tId as unique 2. Why it is not creating the foreign key relation on SpeakerId and Speakers table? Thanks

J. Davidson
  • 3,297
  • 13
  • 54
  • 102
  • See this answer on how to validate unique fields and create database indexes - including fields that are nullable http://stackoverflow.com/a/18736484/150342 – Colin Oct 08 '14 at 08:02

2 Answers2

0

For problem number 2 you need to add a navigational property to your entity:

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
}  

Depending on the Relationship this can also be public virtual ICollection<Speaker> Speakers { get; set;} Vice Versa for the Speaker entity:public virtual Brief Brief { get; set;} ` or the ICollection for n:m / 1:m relations

The unique constraint on non key columns should not be implemented as of yet based on http://entityframework.codeplex.com/workitem/299

Further reading / related questions:

Community
  • 1
  • 1
Marco
  • 22,856
  • 9
  • 75
  • 124
0
  1. See Unique key with EF code first Dependent on the EF version you can set an attribute on the property.

  2. Use a navigational property so EF can determine the relation. Note that the virtual keyword denotes lazy loading. See Entity Framework Code First Lazy Loading

Community
  • 1
  • 1
Zeratul75
  • 36
  • 2