具有DB First Entity Framework和AutoMapper的C#控制台应用程序无法将模型转换为DbModel

时间:2019-01-21 21:59:55

标签: c# entity-framework automapper

我正在尝试运行一个基本的控制台应用程序,以便可以使用DB First Entity Framework和AutoMapper将用户输入的数据保存到现有数据库中,但是当我尝试将本地模型保存回数据库时,由于无法进行编译,它无法将本地模型转换为数据库模型。

EF生成了以下类:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace DbModels
{
    using System;
    using System.Collections.Generic;

    public partial class contact
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public contact()
        {
            this.address = new HashSet<address>();
        }

        public System.Guid id { get; set; }
        public string full_name { get; set; }
        public string email { get; set; }
        public string mobile_phone { get; set; }
        public System.DateTime created_timestamp { get; set; }
        public System.DateTime modified_time_stamp { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<address> address { get; set; }
    }
}

然后我有了一个本地contact模型:

using System;
namespace AppModels
{
    public class contact
    {
        public contact()
        {
            id = new Guid();
            created_timestamp = DateTime.Now;
            modified_time_stamp = DateTime.Now;
        }
        public Guid id { get; }
        public string full_name { get; set; }
        public string email { get; set; }
        public string mobile_phone { get; set; }
        public DateTime created_timestamp { get; }
        public DateTime modified_time_stamp { get; }

    }
}

在控制台应用程序中,我使用AutoMapper在模型之间创建地图,获取一些用户输入,然后尝试将该输入保存到数据库中:

static void Main(string[] args)
{
    var config = new MapperConfiguration(cfg => {
        cfg.CreateMap<DbModels.contact, AppModels.contact>().ReverseMap();
    });

    IMapper mapper = config.CreateMapper();
    var source = new DbModels.contact();
    var dest = mapper.Map<DbModels.contact, AppModels.contact>(source);

    AppModels.contact ContactDetails = new AppModels.contact();
    Console.WriteLine("Enter your name:");
    ContactDetails.full_name = Console.ReadLine();

    Console.WriteLine("Enter your email:");
    ContactDetails.email = Console.ReadLine();

    Console.WriteLine("Enter your phone number:");
    ContactDetails.mobile_phone = Console.ReadLine();

    using (var dbcontext = new myDbContext())
    {
        dbcontext.contact.Add(mapper.Map<DbModels.contact,AppModels.contact>(ContactDetails)); // Argument 1: cannot convert from 'AppModels.contact' to 'DbModels.contact' 
        dbcontext.SaveChanges();
    }



}

dbcontext.contact.Add(ContactDetails);行在编译Argument 1: cannot convert from 'AppModels.contact' to 'DbModels.contact'时引发错误,我在Web应用程序中使用了几乎相同的automapper / EF代码,并且一切正常,似乎AutoMapper并没有告诉EntityFramework是它可以使用的模型映射。

1 个答案:

答案 0 :(得分:0)

您的异常状态为“参数1:无法从'AppModels.contact'转换为'DbModels.contact'”。

尽管,您的映射是从DbModel版本到AppModel版本。不知道您使用的是哪个版本的AM,但是有一个ReverseMap函数,您可以将其链接到地图调用的末尾,并使其同时进行。

这是将其添加到AM的提交。 https://github.com/AutoMapper/AutoMapper/commit/bff6e2aa49af3e7b50f527376da48924efa7d81e

供其他人将来参考,以下是ReverseMap方法的文档: http://docs.automapper.org/en/stable/Reverse-Mapping-and-Unflattening.html

更新:我刚刚注意到您正在使用Map()而不是CreateMap()。 AM是一个两步过程... 1创建地图,1完成地图。您仅在初始化的第二步,但缺少第一部分。我还更新了下面的示例,因为我刚刚复制了您的代码并添加了Reverse调用。

在(初始化方法)中更改此行:

var dest = mapper.Map<DbModels.contact, AppModels.contact>(source);

对此:

var dest = mapper.CreateMap<DbModels.contact, AppModels.contact>(source).ReverseMap();

然后在您的保存中更改它:

using (var dbcontext = new myDbContext())
    {
        dbcontext.contact.Add(ContactDetails); // Argument 1: cannot convert from 'AppModels.contact' to 'DbModels.contact' 
        dbcontext.SaveChanges();
    }

对此:

using (var dbcontext = new myDbContext())
    {
        dbcontext.contact.Add(AM.Map<Src, Dest>(ContactDetails)); // This is pseudo...you have to have the mapper in scope as was pointed out in the comments of your ? and I don't think the Src type is required in most versions of AM.
        dbcontext.SaveChanges();
    }

以下是其用法示例:

var dest = mapper.CreateMap<DbModels.contact, AppModels.contact>(source).ReverseMap();