piątek, 11 września 2009

Linq To Entity - tips

I show you a few tips, which can make your work with linq to entity easier.
This is hypothetical datebase schema, it will be usefull for explaining tips.


Below you see the same datebase in Entity Data Model.



Simple way to get persons and their interests is:


public class PersonInterests
{
public string Person { get; set; }
public List<string> Interest { get; set; }
}
...
testEntities te = new testEntities();
List<PersonInterests> persons = new List<PersonInterests>();
foreach (var item in te.Persons.Include("Jobs"))
{
var interests = te.Interests.
Where(p => p.Persons.Any(a => a.Id == item.Id)).
Select(r => r.Interest).
ToList<string>();

persons.Add(new PersonInterests()
{
Interest = interests,
Person = item.Name,
Id=item.Id,
Job = item.Jobs.Name
});
}

...

If you want to uptate interests for person you don't have to query against database, for example:


...
Persons person = te.Persons.Where(i => i.Id == personID).FirstOrDefault();
person.Interests.Clear(); //clear all interests
//add interest where id=2
person.Interests.Add(te.Interests.Where(i=>i.Id==2).FirstOrDefault());
te.SaveChanges();
...

You can do that:


...
Persons person = te.Persons.Where(i => i.Id == aa.Id).FirstOrDefault();
person.Interests.Clear();
Interests inte = new Interests() { Id = 2 };
te.AttachTo("Interests", inte);
person.Interests.Add(inte);
....


Also you can update Jobs in this way:


...
//change job on that with Id=3
person.JobsReference.EntityKey = new EntityKey("testEntities.Jobs", "Id", 3);
te.SaveChanges();