![](/img/trans.png)
[英]AutoMapper mapping int[] or List<int> from ViewModel to a List<Type> in Domain Model
[英]Automapper mapping Flags Enum from ViewModel to Domain model
在嘗試使用AutoMapper在我的ViewModel和我的域模型之間進行轉換時,我注意到它與標記Flags屬性的Enums不兼容。
這是類的快速模型:
視圖模型:
public class TestViewModel
{
// array of individual Enum values
public TestEnum[] TestEnum { get; set; }
}
領域模型:
public class TestModel
{
// single Enum marked with flags attribute
public TestEnum TestEnum { get; set; }
}
枚舉:
[Flags]
public enum TestEnum
{
Test1,
Test2,
Test3,
Test4
}
這就是我想要做的。 我想我需要在我的Automapper配置中使用某種自定義解析器,因為它在我執行Mapper.Map()時會拋出異常。
我的問題:我將如何做到這一點?
額外問題:這是處理Viewmodel中的Flags Enums / Bitmasks的最佳實踐 - >域模型(在MVVM方面)嗎? 如果沒有,你會建議采用什么做法(使用AutoMapper或其他方式)?
映射到視圖模型時,您可以嘗試使用Enum.GetValues()
和LINQ來獲取枚舉值列表。 要映射回模型,請嘗試使用Aggregate()
...
Mapper.CreateMap<TestModel, TestViewModel>()
.ForMember(v => v.TestEnum,
x => x.MapFrom(m => Enum.GetValues(typeof(TestEnum))
.Cast<TestEnum>()
.Where(e => (e & m) > 0)
.ToList()))
.ReverseMap()
.ForMember(m => m.TestEnum,
x => x.MapFrom(v => v.Aggregate((i, j) => i | j));
至於這是否是最好的方法,它實際上取決於視圖模型的使用方式。 目前,視圖模型不包含未設置的標志; 你需要它們來渲染視圖嗎?
我將跳過AutoMapper並進入模型綁定路徑。 如果您正在使用ASP.NET MVC,則可以直接掛鈎到模型綁定,以便將所有值合並為一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.