小编Dan*_*tis的帖子

c#泛型类型和存储库模式

我正在使用存储库模式处理C#MVC应用程序.我使用Unity作为我的IoC,以便在MVC应用程序中实现我的存储库.

我创建了以下泛型类型,目的是最小化我的应用程序中的代码复制.这是一个示例:

public abstract class GenericRepository<T, C> : IDisposable,IGenericRepository<T> where T : class where C : DbContext, new()


public async void AddObjectAsync<T>(T entity) where T : class
    {
        try
        {
            // Validate that that there is not an existing object in the database.
            var x = _context.Entry(entity);
            if (!Exists(entity))
            {
                _context.Set<T>().Add(entity); // Add the entry if it does not exist.
                _context.SaveChanges();
            }
            else
            {
                UpdateObjectAsync(entity); // Update the entry if it did exist.
            }
        }
        catch
        {
            throw;
        }
Run Code Online (Sandbox Code Playgroud)

当我使用TPC或TPH策略时这很有效,但是它不适合TPT策略.一个例子: …

c# generics asp.net-mvc entity-framework

6
推荐指数
1
解决办法
809
查看次数

标签 统计

asp.net-mvc ×1

c# ×1

entity-framework ×1

generics ×1