我在下面有一个接口
public interface IEntity<T>
{
T Id { get; set; }
DateTime Created { get; set; }
DateTime Updated { get; set; }
[Timestamp] byte[] RowVersion { get; set; }
}
该接口由类实现
public partial class UrlRec: IEntity<Int64>
{
public int EntityId { get; set; }
public string EntityName { get; set; }
public string Slug { get; set; }
public bool IsActive { get; set; }
public int LanguageId { get; set; }
public long Id { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
[Timestamp] public byte[] RowVersion { get; set; }
}
我为类UrlRecModel创建了一个ViewModel。如何使用AutoMapper为类的ViewModel编写通用扩展方法,反之亦然。
这是我的视图模型
public partial class UrlRecordModel : BaseIbileHubEntityModel
{
#region Properties
[IbileHubResourceDisplayName("Admin.System.SeNames.Name")]
public string Name { get; set; }
[IbileHubResourceDisplayName("Admin.System.SeNames.EntityId")]
public int EntityId { get; set; }
[IbileHubResourceDisplayName("Admin.System.SeNames.EntityName")]
public string EntityName { get; set; }
[IbileHubResourceDisplayName("Admin.System.SeNames.IsActive")]
public bool IsActive { get; set; }
[IbileHubResourceDisplayName("Admin.System.SeNames.Language")]
public string Language { get; set; }
[IbileHubResourceDisplayName("Admin.System.SeNames.Details")]
public string DetailsUrl { get; set; }
#endregion
}
我已经创建了这两个扩展方法。
public static IEntity<T> ToModel<T>(this IEntityViewModel<T> viewModel)
{
return (IEntity<T>)Mapper.Map(viewModel, viewModel.GetType(), typeof(IEntity<T>));
}
public static IEntityViewModel<T> ToViewModel<T>(this IEntity<T> entity)
{
return (IEntityViewModel<T>)Mapper.Map(entity, entity.GetType(), typeof(IEntityViewModel<T>));
}
我在这里用过。
IEntityViewModel<Int64> entityViewModel = urlRec.ToViewModel<Int64>();
IEntity<Int64> entity = entityViewModel.ToModel<Int64>();
我不知道你的视图模型是什么样子的,所以我创建了一个测试视图模型和界面。
public interface IEntityViewModel<T>
{
T Id { get; set; }
DateTime Created { get; set; }
DateTime Updated { get; set; }
byte[] RowVersion { get; set; }
}
public class UrlRecViewModel : IEntityViewModel<Int64>
{
public int EntityId { get; set; }
public string EntityName { get; set; }
public string Slug { get; set; }
public bool IsActive { get; set; }
public int LanguageId { get; set; }
public long Id { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public byte[] RowVersion { get; set; }
}