Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is not the way I would work with generic repositories. First of all, I would share ObjectContext between ClassARepository, CalssBRepository and other repositories in current request. Using IOC container, using injection and per request behavior is recommended:</p> <p>This is how my generic repositories look like:</p> <pre><code>public interface IRepository&lt;T&gt; { //Retrieves list of items in table IQueryable&lt;T&gt; List(); IQueryable&lt;T&gt; List(params string[] includes); //Creates from detached item void Create(T item); void Delete(int id); T Get(int id); T Get(int id, params string[] includes); void SaveChanges(); } public class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : EntityObject { private ObjectContext _ctx; public Repository(ObjectContext ctx) { _ctx = ctx; } private static string EntitySetName { get { return String.Format(@"{0}Set", typeof(T).Name); } } private ObjectQuery&lt;T&gt; ObjectQueryList() { var list = _ctx.CreateQuery&lt;T&gt;(EntitySetName); return list; } #region IRepository&lt;T&gt; Members public IQueryable&lt;T&gt; List() { return ObjectQueryList().OrderBy(@"it.ID").AsQueryable(); } public IQueryable&lt;T&gt; List(params string[] includes) { var list = ObjectQueryList(); foreach(string include in includes) { list = list.Include(include); } return list; } public void Create(T item) { _ctx.AddObject(EntitySetName, item); } public void Delete(int id) { var item = Get(id); _ctx.DeleteObject(item); } public T Get(int id) { var list = ObjectQueryList(); return list.Where("ID = @0", id).First(); } public T Get(int id, params string[] includes) { var list = List(includes); return list.Where("ID = @0", id).First(); } public void SaveChanges() { _ctx.SaveChanges(); } #endregion } </code></pre> <p>ObjectContext is injected through constructor. List() methods return IQueryable for further processing in business layer (service) objects. Service layer returns List or IEnumerable, so there is no deferred execution in views.</p> <p>This code was created using EF1. EF4 version can be a little different and simpler.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload