1 namespace MyCompany.MyProject.Model
2 {
3 public interface IMyEntities
4 {
5 IQueryable<T> FindAll<T>();
6 ObjectQuery<T> CreateQuery<T>(string query);
7 void Add<T>(T t) where T : IEntityWithKey;
8 void AddTo<T>(T t);
9 void Remove<T>(T t) where T : IEntityWithKey;
10 void Dispose();
11 int SaveChanges();
12 }
13 }
14
15 namespace MyCompany.MyProject.Model
16 {
17 public partial class MyEntities : IMyEntities
18 {
19 public IQueryable<T> FindAll<T>()
20 {
21 return CreateQuery<T>(string.Format("[{0}]", GetEntitySetBase<T>().Name)).OfType<T>();
22 }
23 private EntitySetBase GetEntitySetBase<T>()
24 {
25 Type _b = typeof(T);
26 EntityContainer _c = MetadataWorkspace.GetEntityContainer(DefaultContainerName, DataSpace.CSpace);
27 if (_c == null) throw new ApplicationException("Could not find an EntityContainer");
28 EntitySetBase _e = _c.BaseEntitySets.Where(i => i.ElementType.Name.Equals(_b.Name)).FirstOrDefault();
29 if (_e == null) throw new ApplicationException(string.Format("Could not find a corresponding EntitySetBase for Type '{0}'. Is the specified type an EntityType?", _b.Name));
30 return _e;
31 }
32
33 //... implementation of other methods from interface.
34
35 }
36 }
37
38 namespace MyCompany.MyProject.Model
39 {
40 public interface IRepository<T> where T : IEntityWithKey
41 {
42 ObjectQuery<T> CreateQuery(string query);
43 IQueryable<T> FindAll();
44 void Add(T t);
45 void Delete(T t);
46 }
47 }
48
49 namespace MyCompany.MyProject.Model
50 {
51 public class RepositoryBase<T> : IRepository<T> where T : IEntityWithKey
52 {
53 [Dependency]
54 public IMyEntities _entities { get; set; }
55
56 public RepositoryBase()
57 {
58 }
59
60 public IQueryable<T> FindAll()
61 {
62 return _entities.FindAll<T>();
63 }
64
65 public ObjectQuery<T> CreateQuery(string query)
66 {
67 return _entities.CreateQuery<T>(query);
68 }
69
70 public void Add(T t)
71 {
72 _entities.AddTo(t);
73 }
74
75 public void Delete(T t)
76 {
77 _entities.Remove(t);
78 }
79 }
80 }
81
82 namespace MyCompany.MyProject.Model
83 {
84 public class ResourceRepository : RepositoryBase<Resource>, IResourceRepository //here Resource is an IEntityWithKey
85 {
86 public ResourceRepository() : base()
87 {
88 }
89
90 public Resource GetResourceById(int resourceid)
91 {
92 return _entities.FindAll<Resource>().Where(r => r.ResourceId == resourceid).FirstOrDefault<Resource>();
93 }
94 }
95 }