映射后无法保存插入的数据

时间:2019-06-14 05:14:40

标签: c# asp.net asp.net-mvc automapper unit-of-work

我正在尝试创建一个非常简单的C#程序来插入数据。

这是服务文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using DataAccess;
using DataAccess.UoW;
using Model;

namespace ClassLibrary1
{
    public class Service
    {
        private readonly Unit _uow;

        public Service()
        {
            _uow = new Unit();
        }

        public bool CreateEmp(Mdl insertEntity)
        {
            var config = new MapperConfiguration(cfg =>
                             {
                                 cfg.CreateMap<Mdl, Table_1>();
                             });

            IMapper mapper = config.CreateMapper();

            var Empinsert = mapper.Map<Mdl, Table_1>(insertEntity);
            _uow.Register.Insert(Empinsert);

            _uow.Save();  //this line shows error

            return false;
        }
    }
}

工作单元:

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

namespace DataAccess.UoW
{
    public class Unit
    {
        private guruEntities _context = null;
        private Repository<Table_1> _register;

        public Unit()
        {
            _context = new guruEntities();
        }
        public Repository<Table_1> Register
        {
            get
            {
                if (this._register == null)
                    this._register = new Repository<Table_1>(_context);
                return _register;
            }
        }
    }
}

这是我得到的错误:

  

C#'Unit'不包含'Save'的定义,并且找不到可以接受的扩展方法'Save'接受类型为'Unit'的第一个参数(是否缺少using指令或程序集引用?)< / p>

1 个答案:

答案 0 :(得分:1)

您必须像这样在单元类中添加保存方法

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

为了更好地理解您可以从下面的链接引用Unitofwork类

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application