我正在嘗試構建一個簡單的應用程式,我可以在其中存盤和檢索有關某些設備及其用戶的一些詳細資訊,例如庫存。但是當我嘗試向其所有者顯示設備串列時,Automapper 會引發此錯誤:
AutoMapperMappingException: Missing type map configuration or unsupported mapping.
我不明白我在這里做錯了什么。我該如何處理?
啟動檔案
builder.Services.AddAutoMapper(typeof(MapConfig));
builder.Services.AddControllersWithViews();
var app = builder.Build();
地圖組態檔
public class MapConfig : Profile
{
public MapConfig()
{
CreateMap<Asset, AssetVM>().ReverseMap();
CreateMap<AppUser, AppUsersVM>().ReverseMap();
}
}
資產.Cs
public class Asset
{
public int Id { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public string? ProductNumber { get; set; }
public string? SerialNumber { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public bool IsAssigned { get; set; }
public string? ISN { get; set; }
public string Status { get; set; }
public bool IsInsured { get; set; }
public string Condition { get; set; }
[ForeignKey("UserId")]
public AppUser AppUser { get; set; }
public string? UserId { get; set; }
}
資產虛擬機
public class AssetVM
{
public int Id { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
[Display(Name ="Product Number")]
public string? ProductNumber { get; set; }
[Display(Name ="Serial Number")]
public string? SerialNumber { get; set; }
[Display(Name ="Date Created")]
[DataType(DataType.Date)]
public DateTime DateCreated { get; set; }
[Display(Name = "Date Modified")]
[DataType(DataType.Date)]
public DateTime DateModified { get; set; }
[Display(Name ="Assigned")]
public bool IsAssigned { get; set; }
public string? ISN { get; set; }
[Required]
public string Status { get; set; }
[Display(Name ="Has Insurance")]
public bool IsInsured { get; set; }
[Required]
public string Condition { get; set; }
public string? UserId { get; set; }
public SelectList? AppUsersList { get; set; }
public AppUsersVM AppUsers { get; set; }
}
這是我獲取和映射要顯示在頁面上的資料的方式:
public async Task<AssetVM> GetAssets()
{
var asset = await context.Assets.Include(q => q.AppUser).ToListAsync();
var model = mapper.Map<AssetVM>(asset);
return model;
}
最后,我將 GetAssets 方法的結果回傳到控制器中的視圖:
var model = await assetRepository.GetAssets();
return View(model);
uj5u.com熱心網友回復:
好吧,我發現我做錯了什么。這就是我所做的:
由于我在 GetAssets 方法中查詢資料庫后獲得了一個串列,因此我不得不將映射更改為:
var model = mapper.Map<List<AssetVM>>(asset);
為了能夠回傳這個模型,我還必須將我的方法宣告更改為:
public async Task<List<AssetVM>> GetAssets()
此更改使其作業,但我沒有獲得使用該資產的用戶的詳細資訊。這是由于我的 AssetVM 視圖模型中的拼寫錯誤。
public AppUsersVM AppUser { get; set; }
這些都是我必須做的改變。成為一名稱職的程式員還有很長的路要走,所以如果你讓我知道我的邏輯是否有任何缺陷或任何建議,我會很高興。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/401924.html
標籤:C# asp.net核心 自动映射器 模型绑定 .net-6.0
