Entity Framework 41-Collection Relations

Part 1: First Steps
Part 2: Managing Relations

Relations between objects are not limited to an object that keep a reference to another object (as seen in part 2), but I can have an object that contains a list of other objects. This is the classic RDBMS rough equivalent of the One-To-Many relation. I decided that my Warrior can carry a certain number of items, so I defined an Item class and a property on Warrior class to hold reference to a list of Items.

1
2
3
4
5
6
private IList<Item> _items;
public IList<Item> Items
{
get { return _items ?? (_items = new List<Item>()); }
set { _items = value; }
}

This is a standard implementation of a property that permits me to establish that a Warrior can have a list of Items. In the Getter part I use lazy initialization, so I can simply add an IList<Item> from external code, or I can simply let the object auto-initialize a standard list for me. This is the code that actually adds some item to a Warrior.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Warrior Caramon;
using (var db = new BattlefieldContext())
{
Caramon = new Warrior { Name = "Caramon", ExperiencePoints = 342553 };
Caramon.ActiveWeapon = new Weapon() { Damage = 10, Size = 3 };
Caramon.Items.Add(new Item() { Name = "Ring of invisibility" });
Caramon.Items.Add(new Item() { Name = "Health Potion" });
db.Warriors.Add(Caramon);
db.SaveChanges();
}

Again I want to point out that I did not make any other changes to the BattlefieldContext or to something related to persistence, I just defined the Item class and the Items property on the Warrior class, but I’m able to save everything to the database without writing any other line of code. Here is the query generated by EF.

image

Figure 1: Generated query to insert a warrior with two items.

This is the Database Schema that EF created to persist my objects.

image

Figure 2: The database schema to persist Warrior and Items

As you can see, EF created the Warrior_id column on the Items table to be able to keep the relation between items and warriors.

I want to strongly point out that this is nor DDD nor Domain Modeling, I’m simply using EF4.1 like a Super Dataset, to avoid writing CRUD. My primary reason for this little tutorial is moving people from HandWritten SQL code or from old style Dataset to something more flexible and more object oriented.

Alk.

Tags: Entity Framework