简体   繁体   English

使用DbSet在Entity Framework中创建新对象 <T> 。创造()

[英]Creating new objects in Entity Framework using DbSet<T>.Create()

I am migrating a project from Linq-to-SQL to Entity Framework with POCO's, and I'm not sure how should I be creating new objects now in EF. 我正在使用POCO将项目从Linq-to-SQL迁移到Entity Framework,但不确定现在应该如何在EF中创建新对象。

On the surface DbSet<T>.Create() , which creates a dynamic proxy, looks like the better way because it helps me with two-way binding automatically (If I build my POCO's correctly), but from what I saw while browsing open source projects, most just use the standard ctor new T() . 在表面上创建动态代理的DbSet<T>.Create()看起来更好,因为它可以帮助我自动进行双向绑定(如果我正确构建了POCO的话),但是从浏览打开时看到的源项目,大多数只使用标准ctor new T()

The only con I can think of in using DbSet<T>.Create() is that it makes my code somewhat coupled to EF. 在使用DbSet<T>.Create() ,我唯一想到的DbSet<T>.Create()是,它使我的代码有点与EF耦合。

Is there anything else that I am missing? 还有什么我想念的吗?

Which way will help me in creating a testable, robust software more easily? 哪种方法可以帮助我更轻松地创建可测试的,功能强大的软件?

You probably need to think about abstracting the EF code away from the rest of your non-EF code, so you can replace it as needed in order to do your testing. 您可能需要考虑从其他非EF代码中抽象出EF代码,因此可以根据需要替换它以进行测试。

One of the ways (and the way I do it) is to use a generic repository: 一种方法(也是我这样做的方法)是使用通用存储库:

public interface IGenericRepository<TContext, TEntity>
    where TEntity : class, IEntity
    where TContext : IDbContext
{
    TEntity NewEntity();

}

public class GenericRepository<TContext, TEntity> : IGenericRepository<TContext, TEntity> 
    where TEntity : class, IEntity 
    where TContext : IDbContext
{
    private readonly IDbContext _context;

    public GenericRepository(IUnitOfWork<TContext> uow)
    {
        _context = uow.Context;
    }

    public TEntity NewEntity()
    {
        var t = _context.Set<TEntity>().Create();
        _context.Set<TEntity>().Add(t);
        return t;
    }
}

Note that I have only included the code which directly covers your question - creating a new entity from the DBSet but also hiding the underlying method so you can easily reimplement it in a non-EF fashion. 请注意,我仅包含直接涵盖您的问题的代码-从DBSet创建一个新实体,但还隐藏了基础方法,因此您可以轻松地以非EF方式重新实现它。

You may get a few replies or comments about the use of generic repositories, how they are bad etc - its all opinions rather than facts, investigate the various arguments for and against and come to your own conclusions rather than be brown beaten by other people. 您可能会收到有关通用存储库的使用,它们有多不好的信息等方面的一些答复或评论-它的所有观点而不是事实,调查支持和反对的各种论点并得出自己的结论,而不是被其他人殴打。 I use them to hide the underlying persistence layer (EF, ADO.Net etc), making it easy to push a testing implementation to code further up in the chain if I need to. 我使用它们来隐藏基础的持久层(EF,ADO.Net等),从而在需要时可以轻松地将测试实现推入链中的更高层。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM