C#使用AutoMapper進(jìn)行對象映射的示例代碼
引言
AutoMapper 是一個(gè)對象到對象映射的庫,可以簡化 DTO (Data Transfer Objects) 和實(shí)體類之間的轉(zhuǎn)換。在大型應(yīng)用程序中,通常需要將業(yè)務(wù)實(shí)體映射到視圖模型或 DTO 中,這樣可以減少代碼的重復(fù)性并提高可維護(hù)性。本文將詳細(xì)介紹如何在 C# 項(xiàng)目中使用 AutoMapper,包括安裝、配置、以及示例代碼。
一、安裝 AutoMapper
首先,需要在項(xiàng)目中安裝 AutoMapper,可以使用 NuGet Package Manager 進(jìn)行安裝。
在 Visual Studio 中打開 NuGet 包管理控制臺,然后運(yùn)行以下命令:
Install-Package AutoMapper
或者通過 NuGet 管理器搜索 AutoMapper 并進(jìn)行安裝。
二、配置 AutoMapper
安裝完成后,需要配置 AutoMapper。通常在應(yīng)用程序啟動(dòng)時(shí)配置,可以在 ASP.NET Core 的 Startup 類中配置,或在普通的控制臺應(yīng)用程序的入口處配置。
定義模型和 DTO
讓我們首先定義一個(gè)簡單的模型類和對應(yīng)的 DTO 類。
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class UserDto
{
public int Id { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
}
創(chuàng)建映射配置
接下來,我們需要配置對象之間的映射關(guān)系。在 ASP.NET Core 項(xiàng)目中,可以在 Startup.cs 文件中進(jìn)行配置。在控制臺應(yīng)用程序中,可以在 Main 方法中進(jìn)行配置。
using AutoMapper;
using System;
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
// 配置映射關(guān)系
CreateMap<User, UserDto>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"))
.ForMember(dest => dest.Age, opt => opt.MapFrom(src => DateTime.Now.Year - src.DateOfBirth.Year));
}
}
在上面的代碼中,我們定義了一個(gè) AutoMapperProfile 類,它繼承自 Profile,并在構(gòu)造函數(shù)中配置了 User 和 UserDto 之間的映射關(guān)系。
初始化 AutoMapper
然后,我們需要在應(yīng)用程序啟動(dòng)時(shí)初始化 AutoMapper。
在 ASP.NET Core 中,可以在 Startup.cs 中配置:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(Startup));
}
}
在控制臺應(yīng)用程序中,可以在 Main 方法中初始化:
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<AutoMapperProfile>();
});
IMapper mapper = config.CreateMapper();
// 測試映射
var user = new User
{
Id = 1,
FirstName = "John",
LastName = "Doe",
DateOfBirth = new DateTime(1990, 1, 1)
};
var userDto = mapper.Map<UserDto>(user);
Console.WriteLine($"Id: {userDto.Id}, FullName: {userDto.FullName}, Age: {userDto.Age}");
}
}
在上面的代碼中,我們創(chuàng)建了 MapperConfiguration 并添加了我們剛才創(chuàng)建的 AutoMapperProfile。然后,通過 CreateMapper 方法創(chuàng)建一個(gè) IMapper 實(shí)例,并使用它來執(zhí)行映射操作。
三、使用 AutoMapper
有了上述配置后,就可以使用 AutoMapper 進(jìn)行對象映射了。以下是一個(gè)簡單的示例:
var user = new User
{
Id = 1,
FirstName = "John",
LastName = "Doe",
DateOfBirth = new DateTime(1990, 1, 1)
};
var userDto = mapper.Map<UserDto>(user);
Console.WriteLine($"Id: {userDto.Id}, FullName: {userDto.FullName}, Age: {userDto.Age}");
運(yùn)行該代碼后,將輸出:
Id: 1, FullName: John Doe, Age: 34
AutoMapper 自動(dòng)將 User 對象映射到 UserDto 對象,并且根據(jù)配置生成了 FullName 和 Age 的值。
四、總結(jié)
通過以上示例,您已經(jīng)學(xué)習(xí)了如何在 C# 中使用 AutoMapper 進(jìn)行對象映射。AutoMapper 是一個(gè)非常強(qiáng)大的工具,它可以減少手動(dòng)編寫映射代碼的工作量,特別是在復(fù)雜項(xiàng)目中更是如此。希望本文對您有所幫助!
完整代碼示例:
using AutoMapper;
using System;
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class UserDto
{
public int Id { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
}
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<User, UserDto>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"))
.ForMember(dest => dest.Age, opt => opt.MapFrom(src => DateTime.Now.Year - src.DateOfBirth.Year));
}
}
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<AutoMapperProfile>();
});
IMapper mapper = config.CreateMapper();
var user = new User
{
Id = 1,
FirstName = "John",
LastName = "Doe",
DateOfBirth = new DateTime(1990, 1, 1)
};
var userDto = mapper.Map<UserDto>(user);
Console.WriteLine($"Id: {userDto.Id}, FullName: {userDto.FullName}, Age: {userDto.Age}");
}
}
這段代碼可以直接復(fù)制到您的項(xiàng)目中并運(yùn)行,幫助您快速掌握 AutoMapper 的使用。
以上就是C#使用AutoMapper進(jìn)行對象映射的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于C# AutoMapper對象映射的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#爬取動(dòng)態(tài)網(wǎng)頁上信息得流程步驟
動(dòng)態(tài)內(nèi)容網(wǎng)站使用 JavaScript 腳本動(dòng)態(tài)檢索和渲染數(shù)據(jù),爬取信息時(shí)需要模擬瀏覽器行為,否則獲取到的源碼基本是空的,這篇文章主要給大家詳細(xì)介紹了C#爬取動(dòng)態(tài)網(wǎng)頁上信息得流程步驟,需要的朋友可以參考下2024-10-10
C#中String和StringBuilder的簡介與區(qū)別
今天小編就為大家分享一篇關(guān)于C#中String和StringBuilder的簡介與區(qū)別,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-10-10
datatable生成excel和excel插入圖片示例詳解
excel導(dǎo)出在C#代碼中應(yīng)用己經(jīng)很廣泛了,下面講了datatable生成excel、復(fù)制sheet頁、刪除sheet頁、選中sheet頁、另存excel文件、excel中插入圖片等功能2014-01-01
.NET(C#):Emit創(chuàng)建異常處理的方法
.NET(C#):Emit創(chuàng)建異常處理的方法,需要的朋友可以參考一下2013-04-04
C#實(shí)現(xiàn)窗體間傳遞數(shù)據(jù)實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)窗體間傳遞數(shù)據(jù)實(shí)例,需要的朋友可以參考下2014-07-07

