0

EF Code First - Model

I have 2 classes:

public class Alias
{
    public int id { set; get; }
    public string Name { set; get; }
    public ICollection<Tweet> Tweets { set; get; }
}

public class Tweet
{
   public int id {set;get;}
   public Alias Author { set; get; }
}

It creates a Author_Id (FK) in the Tweet class. Okay makes sense, because it has a relationship between two models. But how come it doesn't create Tweet_Id (FK) in the Alias class? or is it because I am using ICollection? why it creates a FK in Tweet class and not vice versa?

What keyword tells the EF to create a FK in its model

Also I tried the below code and it fails....

public class Alias
{
    public int id { set; get; }
    public string Name { set; get; }
    public Tweet Tweets { set; get; }
}

public class Tweet
{
   public int id {set;get;}
   public Alias Author { set; get; }
}

I am trying to understand how the model works, how and when it creates a FK? ... please provide me a brief explanation... Thank you in advance!

dknaack
  • 60,192
  • 27
  • 155
  • 202
Benk
  • 1,284
  • 6
  • 33
  • 64
  • Your doing Entity Framework Code First, right ? – dknaack Jan 05 '12 at 23:26
  • 1
    This is core knowledge about relational databases so if you don't understand these concepts you should stop working with EF and try to learn something about relational databases. You will not be able to use EF correctly without at least basic understanding to relational concepts. – Ladislav Mrnka Jan 06 '12 at 09:11

1 Answers1

0

SQL doesn't need a foreign key on both tables. There isn't a concept of a direction the way there is in C#.

The Tweet table needs an id to say which Alias it's connected to. From that you can query all tweets that were made by that alias pretty easily.

If there were a Tweet_Id on the Alias table, what would be set to once there was a second tweet made by the same person?

David Hogue
  • 1,791
  • 1
  • 14
  • 23
  • Thx David, your answer makes sense since it's 1..many. But what If I had 1 to 0..1 who would have the FK? How do you choose which model would contain the FK? If you could also provide a sample example of how you would write both the models based (1 to 0..1) that would be very helpful... Thanks again – Benk Jan 09 '12 at 15:24
  • 0..1: I'm not so sure how it would map. I'd need to try it and see. Technically I think you could put the foreign key on either end. In SQL, making a nullable Tweet_Id in the Alias table might be more explicit, but I don't know EF well enough yet to say what it would do. I can try to get an example, but I can't promise it'll be real soon... – David Hogue Jan 10 '12 at 00:58