我的应用分为4层:
Core
:我放了一些通用和接口类。Model
:我的代码优先类,以及与域相关的其他类,例如实体配置和存储库等。Vm
:视图模型的实时位置。引用Model
。Desktop
:桌面应用程序所在的位置。引用Vm
。我已将实体框架安装到Model
,ViewModel
和Desktop
。
我的问题是:仅仅将其安装到Model
是否足够?为什么要重复一次?
[编辑]
以下是存储库和 UnitOfWrok 的实现( IRepository 和存储库将位于核心):
public interface IRepository<TEntity> where TEntity : class
{
TEntity Get(int id);
IEnumerable<TEntity> GetAll();
IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
TEntity SingleOrDefault(Expression<Func<TEntity, bool>> predicate);
void Add(TEntity entity);
void AddRange(IEnumerable<TEntity> entities);
void Remove(TEntity entity);
void RemoveRange(IEnumerable<TEntity> entities);
}
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly DbContext Context;
public Repository(DbContext context)
{
Context = context;
}
public TEntity Get(int id)
{
return Context.Set<TEntity>().Find(id);
}
and so on...
}
现在,新的下一个接口和分类将在模型
public interface ICountryRepository : IRepository<Country> {}
public class CountryRepository : Repository<Country>, ICountryRepository
{
public CountryRepository(CmsDbContext cmsDbContext)
: base(cmsDbContext) {}
}
interface IUnitOfWork : IDisposable
{
ICountryRepository CountryRepository { get; }
}
public class UnitOfWork : IUnitOfWork
{
private readonly CmsDbContext _context;
public UnitOfWork(CmsDbContext context)
{
_context = context;
CountryRepository = new CountryRepository(_context);
}
public ICountryRepository CountryRepository { get; private set; }
public int Commit()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
现在,在我的ViewModel
中private UnitOfWork Currentunitofwork;
Currentunitofwork = new UnitOfWork(new CmsDbContext());
我在udemy中描述了一位导师。
这种分离是否正确?
答案 0 :(得分:1)
将所有存储库(实体框架)方法移到Core中的接口后面,并在ViewModel项目中引用这些接口。
Core.dll
public class SomeModel {}
public interface ISomeModelRepositoryService
{
SomeModel GetById(int id);
void Save(SomeModel model);
}
Model.dll - 这个项目实现了Core的接口,只包含数据库方法(在你的情况下是实体框架)
public class SomeModelRepositoryService : ISomeModelRepositoryService
{
public SomeModel GetById(int id)
{
//Entity framework code
}
public void Save(SomeModel model)
{
//Entity framework code
}
}
ViewModel.dll
public class SomeModelViewModel
{
private ISomeModelRepositoryService _RepositoryService;
public SomeModel Model { get; set; }
public SomeModelViewModel(ISomeModelRepositoryService repositoryService)
{
_RepositoryService = repositoryService;
}
public void Save()
{
_RepositoryService.Save(this.Model);
}
}
在top startUp项目中创建存储库实现实例(例如Main方法)并将其作为参数放到ViewModel中:
ISomeModelRepositoryService repositoryService = new SomeModelRepositoryService();
SomeModelViewModel viewmodel = new SomeModelViewModel(repositoryService);
仅使用此方法&#34; Model.dll&#34;需要引用实体框架