简体   繁体   English

MVC 4中的AutoMapper无限循环

[英]AutoMapper infinity Loop In MVC 4

I'm getting a stack overflow exception in my mvc project... 我的mvc项目中出现堆栈溢出异常...

I Call MapInitialize.Initialize in Global.asax file 我在Global.asax文件中调用MapInitialize.Initialize

this is MapInitialize class... 这是MapInitialize类...

using AutoMapper;
using Model1 = Project.BusinessLogic.Model;
using Model2 = Project.DataAccess.Model;

namespace Project.BusinessLogic
{
    public static class MapInitialize
    {
        public static void Initialize()
        {
            Mapper.CreateMap<Model1.table, Model2.table>();
        }
    }
}

this is Model1.table tables fields with partial class 这是带有部分类的Model1.table表字段

    namespace Project.BusinessLogic
    {
        public partial class table
        {
            public int ID { get; set; }
            public string field1{ get; set; }
            public string field2 { get; set; }
            public string field3{ get; set; }

            public virtual table2 table2 { get; set; }
        }
    }


    using Model = Project.DataAccess.Model;
    namespace Project.BusinessLogic
    {        
        public partial class table
        {
             public static implicit operator Model.table(table model)
             {
                 if (model == null) return null;
                 return Mapper.Map<table, Model.table>(model);
             }

             public static implicit operator table(Model.table model)
             {
                 if (model == null) return null;
                 return Mapper.Map<Model.table, table>(model);
             }
         }
     }

and I getting exception... 我得到了例外...

 public Result<Model.table> Createtable(Model.table model)
{
    var result = new Result<Model.table>();
    try
    {
        model.field1 = "foo";
        model.field2 = "foo2";
        var res = Ctx.table.Add(model);
        Ctx.SaveChanges();
        result.Value = res; ***// here is infinity loop exception*** 
        result.Success = result.Value != null;
        return result;
    }
    catch (Exception ex)
    {
       Console.Log(ex);
    }
}

It's not always a good idea to be using casting operators as it makes it very difficult to see what code is being executed. 使用强制转换运算符并不总是一个好主意,因为它很难查看正在执行什么代码。 When you do use them, it's a good idea not to have two-way implicit cast operators. 当您使用它们时,最好不要使用双向implicit强制转换运算符。 Try and make one of them explicit . 尝试使其中一个explicit That should reduce the chance of an infinite loop. 那应该减少无限循环的机会。

That being said, I think in your case it would be far clearer to someone else reading the code if you were to add a Mapper.Map call explicitly instead of relying on cast operators. 话虽这么说,但是我认为如果您要显式添加Mapper.Map调用而不是依赖于Mapper.Map运算符,那么对于其他人来说,阅读代码会更加清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM