MVC中的AutoMapper无限循环
本文关键字:无限循环 AutoMapper 中的 MVC | 更新日期: 2023-09-27 18:03:40
我得到一个堆栈溢出异常在我的mvc项目…
调用MapInitialize。在Global中初始化。asax文件
这是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>();
}
}
}
这是模型1。表中包含部分类
的字段 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);
}
}
使用强制转换操作符并不总是一个好主意,因为它使得很难看到正在执行的代码。当您确实使用它们时,最好不要使用双向implicit
强制转换操作符。试着让其中一个变成explicit
。这样可以减少无限循环的可能性。
话虽如此,我认为在您的情况下,如果您显式地添加Mapper.Map
调用而不是依赖强制转换操作符,则对其他人阅读代码会更清楚。