存储库模式和一对多关系

时间:2015-03-09 19:03:47

标签: c# .net entity-framework

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

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);
   }
}

我的班级

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();
        }
     }
 }

非常感谢你的帮助。祝你有个美好的一天,没有错误)

2 个答案:

答案 0 :(得分:1)

将上下文添加到存储库,以便您可以实现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足够聪明,可以注意到您在该类别中添加了一个子项,并将其标记为已添加。在保存更改时,它会将其与所需的外键一起插入数据库。

答案 1 :(得分:0)

我认为您需要将类别属性添加到图书对象

public virtual Category BookCategory { get; set; }

以便实现一对多的关系