EF CORE类库 [英] EF CORE class library

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

问题描述

嗨开发者,

我正在使用EF核心创建类库项目。 EF核心类库中没有任何干净的帮助可以在类库项目中使用DI,如何通过添加引用在其他项目中使用EF核心库项目。在EF核心类库项目上有没有可用的
的干净解决方案?

I am creating class library project using EF core. There is no any clean help available on EF core class library to use DI in class library project, How to use EF core library project in other projects by adding references. Is there any clean solution available on EF core class library project?

同样使用事务来保存多个表中的数据是有效的是否在Ef中?

Also using transaction to save data in mulitple tables is valid in Ef or not?

如果在事务中执行了多个CRUD操作,那么哪种策略可以避免死锁?

if more then one CRUD operation is executing within transaction then which strategy is good to avoid deadlock?

推荐答案

我正在使用EF核心创建类库项目。 EF核心类库中没有任何干净的帮助可以在类库项目中使用DI,如何通过添加引用在其他项目中使用EF核心库项目。在EF核心类库项目中是否有
可用的任何干净解决方案?

是的,它们是数据持久性的有效设计模式,它没有'是否使用了像EF Core这样的ORM。

Yes they are valid design patterns for data persistence, and it doesn't matter if an ORM like EF Core is being used or not.

1)选项是 关于使用工作单元模式和存储库模式,这是一个classlib项目。 请注意,UoW和Repository模式不必使用像EF这样的ORM, 并且存储库不需要是通用的。

1) Option is  about using the Unit of Work pattern and the Repository pattern, which is a classlib project.  Note that the UoW and Repository pattern do not have to be using an ORM like EF,  and the Repository doesn't need to be generic.

大多数开发人员真的不知道如何使用存储库模式, 并且他们错误地将通用存储库模式视为持久性模式,但事实并非如此。存储库是域的一部分,该域使用持久性/映射模式进行
CRUD操作。

Most developers really don't know how to use the Repository pattern,  and they mistakenly consider the generic Repository pattern as a persistence pattern, but it is not. The Repository is part of the domain that uses a persistence/mapping pattern for CRUD operations.

https:// martinfowler.com/eaaCatalog/repository.html

<复制>

<copied>

存储库在域和数据映射层之间进行调解,其作用类似于内存中的域对象集合。客户端对象以声明方式构造查询规范,并将它们提交给Repository以满足要求。可以将对象添加到存储库中以及从存储库中删除对象,因为它们可以从简单的对象集合中添加,并且由存储库封装的映射代码将在后台执行适当的操作。从概念上讲,存储库封装了持久存储在数据存储中的对象集
以及对它们执行的操作,从而提供了更加面向对象的持久层视图。存储库还支持在域和数据映射
层之间实现清晰分离和单向依赖的目标。

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.

< end>

<end>

https://martinfowler.com/eaaCatalog/dataMapper.html

https://programmingwithmosh.com/entity-framework/common-mistakes-with-the-repository-pattern/

https://blog.sapiensworks.com/post/2012/11/01/Repository-vs-DAO.aspx

https://blog.sapiensworks.com/post/2012/11/01/Repository-vs-DAO.aspx

选项2是使用数据访问层中的数据访问对象模式

Option 2 is to use the Data Access Object pattern in the Data Access Layer

https: //en.wikipedia.org/wiki/Data_access_object

https://en.wikipedia.org/wiki/Data_access_object

https://www.tutorialspoint.com/ design_pattern / data_access_object_pattern.htm

https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

使用事务来保存多个表中的数据在Ef中是否有效?

Also using transaction to save data in mulitple tables is valid in Ef or not?

是的,这是自动的单个SaveChanges()包含记录是系统的持久性范围的所有表使用.Transaction。但是,如果必须跨单个表执行多个SaveChanges,则必须提供包含SaveChanges的System.Transaction.Scope

Yes, which is automatic is a single SaveChanges() encompassing records is all tables for persistence scope that System.Transaction is used. However, if multiple SaveChanges must be done across individual tables, then you must provide the System.Transaction.Scope that encompass the SaveChanges.

i f在事务中执行的CRUD操作多一个,那么哪种策略可以避免死锁?

if more then one CRUD operation is executing within transaction then which strategy is good to avoid deadlock?

https://www.c-sharpcorner.com/UploadFile/ff2f08/prevent-dead-lock-in-entity-framework/

https://www.c-sharpcorner.com/UploadFile/ff2f08/prevent-dead-lock-in-entity-framework/

使用DI进行DAO的示例代码connectionstring,核心风格。并且DAO正在进入Core 2 WebAPI控制器。

An example code that is using DI for the DAO on connectionstring, Core style. And the DAO is being DI into a Core 2 WebAPI controller.

using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using DAL.Models.DB;
using Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

namespace DAL
{
    public class DaoProject :IDaoProject
    {
        private readonly IOptions<ConnectionStrings> _options;
        
        public DaoProject(IOptions<ConnectionStrings> options)
        {
            _options = options;
        }
        public DtoProject GetProjectById(int id)
        {
            var dto = new DtoProject();

            using (var context = new ProjectManagementContext(_options))
            {
                var project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();

                if (project == null) return dto;
                dto.ProjectId = project.ProjectId;
                dto.ClientName = project.ClientName;
                dto.ProjectName = project.ProjectName;
                dto.Technology = project.Technology;
                dto.ProjectType = project.ProjectType;
                dto.UserId = project.UserId;
                dto.StartDate = project.StartDate;
                dto.EndDate = project.EndDate;
                dto.Cost = project.Cost;
            }

            return dto;
        }

        public List<DtoProject> GetProjectsByUserId(string userid)
        {
            var dtos = new List<DtoProject>();

            using (var context = new ProjectManagementContext(_options))
            {
                
                dtos = (from a in context.Projects.Where(a => a.UserId.Contains(userid))
                    select new DtoProject
                    {
                        ProjectId = a.ProjectId,
                        ClientName = a.ClientName,
                        ProjectName = a.ProjectName,
                        Technology = a.Technology,
                        ProjectType = a.ProjectType,
                        UserId = a.UserId,
                        StartDate = a.StartDate,
                        EndDate = a.EndDate,
                        Cost = a.Cost
                    }).ToList();
            }

            return dtos;
        }

        public void CreateProject(DtoProject dto)
        {
            using (var context = new ProjectManagementContext(_options))
            {
                var project = new Projects
                {
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    UserId = dto.UserId,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                };

                context.Projects.Add(project);
                context.SaveChanges();
           }
        }

        public void UpdateProject(DtoProject dto)
        {
            var project = new Projects();
            
            using (var context = new ProjectManagementContext(_options))
            {
               project = (context.Projects.Where(a => a.ProjectId == dto.ProjectId)).SingleOrDefault();
            }

            if (project != null)
            {
                project.ClientName = dto.ClientName;
                project.ProjectName = dto.ProjectName;
                project.Technology = dto.Technology;
                project.ProjectType = dto.ProjectType;
                project.UserId = dto.UserId;
                project.StartDate = dto.StartDate;
                project.EndDate = dto.EndDate;
                project.Cost = dto.Cost;
            }

            using (var dbcontext = new ProjectManagementContext(_options))
            {
                if (project == null) return;
                dbcontext.Entry(project).State = EntityState.Modified;
                dbcontext.SaveChanges();
            }
        }

        public void DeleteProject(int id)
        {
            Projects project;

            using (var context = new ProjectManagementContext(_options))
            {
               project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
            }

            if (project == null) return;

            using (var newContext = new ProjectManagementContext(_options))
            {
               
                var tasks = new DaoTask(_options).GetTasksByProjectId(project.ProjectId);
                using (TransactionScope scope = new TransactionScope())
                {
                    foreach (var task in tasks)
                    {
                        new DaoTask(_options).DeleteTask(task.TaskId);
                    }

                    newContext.Entry(project).State = EntityState.Deleted;
                    newContext.SaveChanges();

                    scope.Complete();
                }
            }
        }
    }
}


using System.Collections.Generic;
using DAL;
using Entities;
using Microsoft.AspNetCore.Mvc;

namespace ProgMgmntCore2Api.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]

    public class ProjectController : ControllerBase, IProjectController
    {
        private readonly IDaoProject _daoProject;

        public ProjectController(IDaoProject daoProject)
        {
            _daoProject = daoProject;
        }

        [HttpGet]
        [Route("GetProjById")]
        public DtoProject GetProjectById(int id)
        {
            return  _daoProject.GetProjectById(id);
        }
        
        [HttpGet]
        [Route("GetProjsByUserId")]
        public List<DtoProject> GetProjectsByUserId(string userid)
        {
            return _daoProject.GetProjectsByUserId(userid);
        }

        [HttpPost]
        [Route("CreateProject")]
        public void Post_CreateProject(DtoProject dto)
        {
            _daoProject.CreateProject(dto);
        }

        [HttpPost]
        [Route("DeleteProject")]
        public void Post_DeleteProject(DtoId dto)
        {
            _daoProject.DeleteProject(dto.Id);
        }

        [HttpPost]
        [Route("UpdateProject")]
        public void Post_UpdateProject(DtoProject dto)
        {
            _daoProject.UpdateProject(dto);
        }
    }
}


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

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