如何在实体框架中使用数据库优先方法使用存储库模式 [英] How to use Repository pattern using Database first approach in entity framework

查看:88
本文介绍了如何在实体框架中使用数据库优先方法使用存储库模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在实体框架中使用数据库优先方法使用存储库模式.我在浏览互联网上可用的资源时有一些想法,但是对于实时应用程序,我不确定如何首先在数据库上自动生成的类上实现存储库模式方法.

How to use Repository pattern using Database first approach in entity framework.I got some idea while going through resources available on internet but for real time applications I am not sure how to implement repository pattern on the auto generated classes from the DB first approach.

我已经遍历了SO中的一些链接,但是我没有一个清晰的主意,我是这个新手. 预先感谢.

I have already gone through some links in SO but I did not get any clear idea.I am new to this one. Thanks in Advance.

推荐答案

代码生成工具将仅修改映射到XML文件的类.您有两种选择:

The code generation tool will only modify the classes that are mapped to the XML files. You have a couple of options:

1)您可以使用局部类来扩展映射的类.使用工具更新代码时,自动化工具不会修改部分类.

1) You can extend the mapped classes by using partial classes. Partial classes will not be modified by the automated tool when updating the code with the tool.

2)您也可以处理配置文件的数据注释和实体配置,请谨慎行事,因为在某些情况下它们可能会发生冲突.在摘要下方:

2) You can also handle data annotations and entity configuration to a Configuration file, just be cautious because in some cases they may conflict. Down below a snippet:

public class YourClassConfiguration : EntityTypeConfiguration<YourClass>
{
    public YourClassConfiguration()
    {
        ToTable("YourTable");
        HasKey(e => e.Property1);
        Property(e => e.Property1).HasColumnName("MyName").HasMaxLength(30);
    }
}

我一直在使用这种方法,说实话,我建议您像以前一样将实现转移到代码优先"方法.以我个人的观点,当设计人员决定创建重复的密钥或不正确地更新XML文件时(这对我来说不止一次),这是维护和修复问题的痛苦.好消息是,您可以避免迁移以及Code First使用的某些功能,并按原样保留数据库结构.一切都可以配置.如果您有兴趣,我可以告诉您更多.

I was working with this approach and honestly, I would suggest you moving your implementation to a Code First approach as I did. In my personal opinion, it's a pain maintaining and fixing problems when the designer decides to create duplicate keys or not updating properly the XML file as it happen to me more than once. The good news is that you can avoid migrations and some of the features used by Code First and preserving the DB structure as is. Everything can be configured. I can tell you more if you are interested.

无论如何,我还将为您附上一个可能有用的GenericRepository模式的简单代码段.我还将强烈建议在您的实现中使用Dependecy Injection(GenericRepository模式要求使用它来解决依赖关系).我会推荐Autofac.它非常稳定并有强大的支持.

Anyhow, I am also attaching you a simple code snippet of a GenericRepository pattern that you may find useful. I will also strongly suggest using dependecy Injection in your implementation (Required by the GenericRepository pattern to resolve dependencies). I would recommend Autofac. It's very stable and has great support.

    public class EntityRepository<T> : IRepository<T>, IDisposable where T
                                    : class, IEntity
    {

        private readonly DbSet<T> dbset;
        private readonly DbContext _context;
        private readonly bool _lazyLoadingEnabled = true;


        public EntityRepository(DbContext context, bool lazyLoadingEnabledEnabled)
        : this(context)
        {
            _lazyLoadingEnabled = lazyLoadingEnabledEnabled;
        }

        public EntityRepository(DbContext context)
        {
            _context = context;
            _context.Configuration.LazyLoadingEnabled = _lazyLoadingEnabled;
            dbset = context.Set<T>();
        }

        public void Add(T entity)
        {
            dbset.Add(entity);
            _context.SaveChanges();
        }

        public void Update(T entity)
        {
            var originalValues = FindOne(x => x.Id == entity.Id);
            _context.Entry(originalValues).CurrentValues.SetValues(entity);
            _context.SaveChanges();
        }

        public void Remove(T entity)
        {
            dbset.Remove(entity);
            _context.SaveChanges();
        }

        public List<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            return dbset.Where(predicate).ToList();
        }

        public T FindOne(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            return dbset.FirstOrDefault(predicate);
        }

        public List<T> FindAll()
        {
            return dbset.ToList();
        }
    }

界面非常简单:

    public interface IRepository<T>
                    where T : class, IEntity
    {
        void Add(T entity);
        void Update(T entity);
        void Remove(T entity);
        T FindOne(Expression<Func<T, bool>> predicate);
        List<T> Find(Expression<Func<T, bool>> predicate);
        List<T> FindAll();
    }

将接口应用于您创建的用于扩展数据库第一类的部分类,您将能够查询存储库中的那些实体.您还可以将属性"添加到存储库界面,以使这些属性可见,并添加使用"id","name"等通用属性(如果适用)进行搜索的通用功能.

Apply the interface to the partial classes you created to extend the database first classes and you will be able to query those entities within the repository. You can also add Properties to the repository interface to have those properties visible and add common functionality of searching using common properties such as Id, name and so on if applicable.

我希望能帮上忙,
卡洛斯

I hope it helps,
Carlos

这篇关于如何在实体框架中使用数据库优先方法使用存储库模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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