Tutorial by Examples

So let's say you have two different entities, something like this: public class Person { public int PersonId { get; set; } public string Name { get; set; } } public class Car { public int CarId { get; set; } public string LicensePlate { get; set; } } public class MyDemoCon...
In the last example, you can see that EF figures out which column is the foreign key and where should it point to. How? By using conventions. Having a property of type Person that is named Person with a PersonId property leads EF to conclude that PersonId is a foreign key, and it points to the prima...
In the previous examples a car cannot exist without a person. What if you wanted the person to be optional from the car side? Well, it's kind of easy, knowing how to do one-to-many. Just change the PersonId in Car to be nullable: public class Car { public int CarId { get; set; } public s...
Let's move on to the other scenario, where every person can have multiple cars and every car can have multiple owners (but again, the relationship is bidirectional). This is a many-to-many relationship. The easiest way is to let EF do it's magic using conventions. Just change the model like this: ...
You might want to rename the fields in the join table to be a little more friendly. You can do this by using the usual configuration methods (again, it doesn't matter which side you do the configuration from): public class CarEntityTypeConfiguration : EntityTypeConfiguration<Car> { publi...
I have to admit, I'm not really a fan of letting EF infer the join table wihtout a join entity. You cannot track extra information to a person-car association (let's say the date from which it is valid), because you can't modify the table. Also, the CarId in the join table is part of the primary ke...

Page 1 of 1