工作单位和EF [英] Unit of Work and EF

查看:56
本文介绍了工作单位和EF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照工作单位"模式进行界面.我的界面如下所示:

I'm making an interface following the Unit of Work pattern. My interface looks like this:

public interface IDataContext : IDisposable
{
    void SaveChanges();   
    TSource Create<TSource>(TSource toCreate) where TSource : class;
    TSource Update<TSource>(TSource toUpdate) where TSource : class;
    bool Delete<TSource>(TSource toDelete) where TSource : class;
    IQueryable<TSource> Query<TSource>();
}

到目前为止,一切都很好.现在,我在使用EF4作为数据提供者的数据层中实现它.我为查询"方法想到了这段代码,但是我认为它不是很干净,我觉得有一种聪明的方法可以做到,但我真的不知道.

So far so good. Now I implement it in my Data Layer, which uses EF4 as data provider. I came up with this code for the "Query" method, but I think it's not very clean, I feel there's a clever way to do it but I can't really figure out.

public IQueryable<TSource> Query<TSource>()
    {
        var type = typeof(TSource);
        IQueryable item = null;

        if (type == typeof(Activity)) item = _entities.ActivitySet;
        if (type == typeof(Company)) item = _entities.CompanySet;
        if (type == typeof(Phase)) item = _entities.PhasesSet;
        if (type == typeof(Project)) item = _entities.ProjectSet;
        if (type == typeof(ProjectState)) item = _entities.ProjectStateSet;
        if (type == typeof(ProjectType)) item = _entities.ProjectTypeSet;
        if (type == typeof(User)) item = _entities.UserSet;
        if (type == typeof(UserType)) item = _entities.UserTypeSet;
        if (item != null) return item as IQueryable<TSource>;

        throw new NotImplementedException(string.Format("Query not implemented for type {0}", type.FullName));
    }

我在这里看到的问题是每次都测试所有IF,尽管我可以将它们以级联的方式进行if-else链接,但对我来说仍然很糟糕.另一个问题是我必须为可能会添加的每个新实体手动添加一行,但这不是我的主要担心.

The problems I see here are all the IFs get tested every time, althought I could chain them in a cascading if-else but still looks pretty awful to me. The other problems is that I have to manually add one line for each new entity that might get added, but it's not my main concern.

有人对此有何好的建议?谢谢.

Anyone has any good advice on this? Thanks.

推荐答案

如果您使用的是EF4,则只需调用CreateObjectSet<>.

If you are using EF4 you can just call CreateObjectSet<>.

using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;

namespace WindowsFormsApplication1
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            var context = new DataContext(new NorthwindEntities());
            var list = context.Query<Customer>().ToList();
            var list2 = context.Query<Customer>().ToList();
        }
    }

    public class DataContext : IDataContext
    {
        private Dictionary<Type, object> _objectSets = new Dictionary<Type,object>();
        private ObjectContext _entities;

        public DataContext(ObjectContext objectContext)
        {
            this._entities = objectContext;
        }

        public IQueryable<T> Query<T>()
            where T : class
        {
            Type entityType = typeof(T);
            ObjectSet<T> objectSet;

            if (this._objectSets.ContainsKey(entityType))
            {
                objectSet = this._objectSets[entityType] as ObjectSet<T>;
            }
            else
            {
                objectSet = this._entities.CreateObjectSet<T>();
                this._objectSets.Add(entityType, objectSet);
            }

            return objectSet;
        }
    }

    interface IDataContext
    {
        IQueryable<T> Query<T>() where T : class;
    }
}

如果您使用的是EF1,则可以调用CreateQuery<>,但是您还需要找到Entity设置名称.

If you are using EF1 you can call CreateQuery<> but you will also need to find the Entity Set Name.

using System;
using System.Collections.Generic;
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Linq;

namespace WindowsFormsApplication2
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            var context = new DataContext(new NorthwindEntities());
            var list = context.Query<Customer>().ToList();
        }
    }

    public class DataContext : IDataContext
    {
        private Dictionary<string, string> _entitySets;
        private ObjectContext _entities;

        public DataContext(ObjectContext objectContext)
        {
            this._entities = objectContext;
        }

        public IQueryable<T> Query<T>()
            where T : class
        {
            return this._entities.CreateQuery<T>(this.GetEntitySetName<T>());
        }

        private string GetEntitySetName<T>()
            where T : class
        {
            if (this._entitySets == null)
            {
                // create a dictionary of the Entity Type/EntitySet Name
                this._entitySets = this._entities.MetadataWorkspace
                                                 .GetItems<EntityContainer>(DataSpace.CSpace)
                                                 .First()
                                                 .BaseEntitySets.OfType<EntitySet>().ToList()
                                                 .ToDictionary(d => d.ElementType.Name, d => d.Name);
            }

            Type entityType = typeof(T);

            // lookup the entity set name based on the entityType
            return this._entitySets[entityType.Name];
        }
    }

    interface IDataContext
    {
        IQueryable<T> Query<T>() where T : class;
    }
}

这篇关于工作单位和EF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆