c# - 存储库模式和一对多关系

标签 c# .net entity-framework

我正在创建一个使用 Entity Framework 的应用程序。我有 2 个具有一对多关系的类。据我所知,我决定使用设计模式存储库,这是一个很好的做法。 我的界面:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace DataAccess.Repository
{
   public interface IRepository<T>
   {
       void Insert(T entity);
       void Delete(T entity);
       IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
       IEnumerable<T> GetAll();
       T GetById(int id);
   }
}

我的类(class)

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using DataAccess.Repository;

namespace DataAccess
{
    public class Repository<T> : IRepository<T>  where T : class
    {
        protected DbSet<T> DbSet;

        public Repository(DbContext datacontext)
        {
            //DbContext.Set Method (Type)
            //Returns a non-generic DbSet instance for access to entities of the given type in the context and the underlying store.
            DbSet = datacontext.Set<T>();
        }

        public void Insert(T entity)
        {
            DbSet.Add(entity);
        }

        public void Delete(T entity)
        {
            DbSet.Remove(entity);
        }

        public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
        {
            return DbSet.Where(predicate);
        }

        public IEnumerable<T> GetAll()
        {
            return DbSet;
        }

        public T GetById(int id)
        {
            return DbSet.Find(id);

        }
    }
}

这是我的两个模型类

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    public class Book
    {

        public int BookId { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public string Ganre { get; set; }
        public int Size { get; set; }
        public string Path { get; set; }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    public  class Category{

        public Category()
        {
            Books = new List<Book>();
        }
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
        virtual public ICollection<Book> Books { get; set; } 
       }
}

但我的问题是,如何将图书添加到类别中? 这是我的实现示例,但书籍未添加到类别中。但是,当我想要获取所有书籍或所有类别时,一切正常。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using Model;
using DataAccess;
namespace TestDB
{
    class Program
    {
        static void Main(string[] args)
        {
            Database.SetInitializer(
                new DropCreateDatabaseIfModelChanges<BookShelfContext>());

            using (var db = new BookShelfContext())
            {
                var book = new Book
                {
                    Author = "Author Name",
                    Ganre = "Ganre",
                    Name = "Book Name",
                    Path = @"Path",
                    Size = 10
                };
                var category = new Category
                {
                    CategoryName = "Interesting"
                };


                var bookrepository = new Repository<Book>(db);
                var categoryrepository = new Repository<Category>(db);

                IEnumerable<Book> books = bookrepository.GetAll();
                IEnumerable<Category> categories = categoryrepository.GetAll();
                //get all books for example
                foreach (var b in books)
                {
                    Console.WriteLine(b.Name);
                }

            }
            Console.ReadKey();
        }
     }
 }

非常感谢您的帮助。祝你有美好的一天,减少错误)

最佳答案

将上下文添加到您的存储库,以便您可以实现 SaveChanges 方法:

protected readonly DbContext context;

    public Repository(DbContext datacontext)
    {
        DbSet = datacontext.Set<T>();
        context = datacontext;
    }

    public void SaveChanges()
    {
        context.SaveChanges();
    }

然后为了将一本书添加到现有的 BookCategory 中,只需将该书添加到该类别的集合中并保存该类别:

var categoryrepository = new Repository<Category>(db);
var myCategory = categoryrepository.GetById(1);
myCategory.Books.Add(book);
categoryrepository.SaveChanges();

记得调用 SaveChanges 以将数据保存在数据库中。 EF 足够聪明,可以注意到您向该类别添加了一个子项,并将其标记为已添加。在保存更改时,它会将它连同所需的外键一起插入到数据库中。

关于c# - 存储库模式和一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28949833/

相关文章:

c# - Parallel.ForEach 比正常的 foreach 慢

c# - Akka.net - 尝试测试重复的预定消息

.net - 使用 Entity Framework 4.0,是否有代码优先数据注释可以为数据库列定义默认值?

c# - VS 2017 中的 MySQL 和 MVC Entity Framework 无法正常工作

使用 .Where() 进行 C# Entity Framework 过滤

c# - 如何从 Entity Framework 的模型元数据中获取树结构

c# - 将 String 写入 Stream 并将其读回不起作用

c# - 数据表数组

c# - 非 DataTable 数据源的 DataGrid MappingName 是什么?

c# - 服务总线触发的 Azure 功能因 System.Threading.Tasks.TaskCanceledException 失败