2

我想通过UserCompany一种方法将我的对象插入数据库。比如将元素传递给这个函数,取它并“插入右表”。

通常在实体(例如 LINQ to XML)中,我会执行以下操作:

db.Company.UsersCompany.Add(UserCompany);
db.SubmitChanges();

UsersCompany但这里的问题是我需要Company在使用.Add(). 我想(因为我想为每种类型的对象/表的插入执行一个函数)摆脱这个。比如有一个:

UserCompany.InsertMySelf();

或者

db.SmartAdd(UserCompany);

它知道如何自动插入表格,在哪里以及如何插入。

是否有可能做到这一点?有什么策略吗?

4

3 回答 3

2

您可以使用泛型解决此问题:

Public Sub AddEntities(Of TEntity)(entities As IEnumerable(Of TEntity))
   For Each ent In entities
       _db.Set(Of TEntity).Add(ent)
   Next
   _db.SaveChanges()
End Sub

抱歉使用 VB... 在 C# 中:

public void AddEntities<TEntity>(IEnumerable<TEntity> entities)
   {
     foreach(ent in entities)
     {
         _db.Set<TEntity>.Add(ent);
     }
     _db.SaveChanges();
   }
于 2013-10-03T17:31:46.640 回答
1

在您Controller按照以下方式为自己定义一个存储库:

public class CompanyController : ApiController
{
    private readonly CompanyRepository _companyRepository;

    public CompanyController()
    {
        _companyRepository= new CompanyRepository(User);
    }

    [HttpPost]
    public Company PostCompany(Company comp)
    {
        _companyRepository.SmartAdd(comp);
    }
}

使用以下定义定义存储库:

public class CompanyRepository : EFContextProvider<CompanyContext>
{
    // Fields which can be used for security within the repository.
    public IPrincipal User { get; private set; }
    public string UserName { get; set; }

    public CompanyRepository (IPrincipal user)
    {
        User = user;
        UserName = user.Identity.Name;
    }

    public DbQuery<Object> SmartAdd(Object obj)
    {
        switch (obj.GetType)
        {
            case "":  // TODO...
              Context.Company.UsersCompany.Add(UserCompany);
                break;

            default:
                break;
        }
    }

必须进行一些调整以适应您自己的需求,但这是一般的想法。

尽管在 switch 中可能存在很多情况,但我假设您无论如何都会进行对象验证和其他事情,因此您也可以在这里轻松地做到这一点。

相关链接:

于 2013-10-03T13:35:36.033 回答
0

您需要查看通用存储库。这种模式通过一个基类提供所有 CRUD。然后,您可以从此类继承以在必要时实现自定义存储库

public class RepositoryBase<T> : IRepository<T> where T : ModelBase
{
    private readonly IUnitOfWork _UnitOfWork;
    //https://stackoverflow.com/questions/4442828/entity-framework-4-ctp-4-ctp-5-generic-repository-pattern-and-unit-testable/4458250#4458250


    protected MyContext Context { get { return _UnitOfWork.Context; } }

    public RepositoryBase(IUnitOfWork unitOfWork)
    {
        _UnitOfWork = unitOfWork;
    }

    public virtual T InsertOrUpdate(T e)
    {
        DbSet<T> dbSet = Context.Set<T>();

        DbEntityEntry<T> entry;
        if (e.GetType().BaseType != null && e.GetType().Namespace == "System.Data.Entity.DynamicProxies")
        {
            //The entity being added is already a proxy type that supports lazy loading
            //just get the context entry
            entry = Context.Entry(e);
        }
        else
        {
            //The entity being added has been created using the "new" operator. 
            //Generate a proxy type to support lazy loading  and attach it
            T instance = dbSet.Create();
            instance.ID = e.ID;
            entry = Context.Entry(instance);
            dbSet.Attach(instance);

            //and set it's values to those of the entity
            entry.CurrentValues.SetValues(e);
            e = instance;
        }

        entry.State = e.ID == default(int) ?
                                EntityState.Added :
                                EntityState.Modified;

        return e;
    }

    public virtual IQueryable<T> All
    {
        get
        {
            return Context.Set<T>(); 
        }
    }

    public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = All;
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query;
    }

    public virtual T Find(int id)
    {
        T e = Context.Set<T>().Find(id);
        if (e == null)
            return null;

        return e;
    }

    public virtual void Delete(int id)
    {
        var e = Context.Set<T>().Find(id);

        if (e != null)
            Context.Set<T>().Remove(e);

    }
}

public abstract class ModelBase
{
    public int ID { get; set; }
}

参考:

存储库和工作单元模式

约翰爸爸的原始来源

使用存储库模式时如何确保创建代理

通用存储库模式

于 2013-10-04T11:40:27.137 回答