我有以下 RecipeModel、IngredientModel 和 RecipePartModel 类,它们代表前端用户的 DTO 类:
public class RecipeModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public string Description { get; set; }
public IEnumerable<RecipePartModel> RecipeParts { get; set; }
}
public class IngredientModel
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class RecipePartModel
{
public Guid Id { get; set; }
public IngredientModel Ingredient { get; set; }
public string Unit { get; set; }
public decimal Quantity { get; set; }
}
这是我的实体类:
public class Recipe : BaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public string Description { get; set; }
public virtual IEnumerable<RecipePart> RecipeParts { get; set; }
}
public class Ingredient : BaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public int Amount { get; set; }
public virtual IEnumerable<RecipePart> RecipeParts { get; set; }
}
public class RecipePart : BaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
public Ingredient Ingredient { get; set; }
public Recipe Recipe { get; set; }
public string Unit { get; set; }
public decimal Quantity { get; set; }
}
我的问题是 - 如何使用 AutoMapper 将 Recipe 映射到 RecipeModel?我尝试了类似的方法,但我认为它很糟糕,因为它只是加入整个数据库的所有 RecipeParts,我是对的吗?
public class DomainProfile : Profile
{
public DomainProfile()
{
CreateMap<Ingredient, IngredientModel>().ReverseMap();
CreateMap<Recipe, RecipeModel>()
.ForMember(x => x.RecipeParts, opt => opt.MapFrom(src => src.RecipeParts));
}
}
最佳答案
要回答有关如何使用 AutoMapper 将一种类型映射到另一种类型的问题,有多种方法可以实现。文档在这里:http://docs.automapper.org/en/stable/Getting-started.html .
我编写了一个控制台应用程序,并使用您的代码以我所知的最快方式使其工作。当我调试这个并检查recipeModel内部时,它引用了带有单个RecipePartModel的RecipePartModel列表。在 RecipePartModel 内部,它引用了 IngredientModel。
static void Main(string[] args)
{
var profile = new DomainProfile();
Mapper.Initialize(cfg => cfg.AddProfile(profile));
var recipe = new Recipe
{
RecipeParts = new List<RecipePart>
{
new RecipePart()
{
Ingredient = new Ingredient()
}
}
};
var recipeModel = Mapper.Map<Recipe, RecipeModel>(recipe);
Console.ReadKey();
}
为了回答您对从数据库获取所有食谱的担忧,如果您使用 Entity Framework ,这取决于您是否启用了延迟加载。延迟加载可确保当您从数据库获取配方时,不会加载配方部分。仅当您稍后在程序流程中直接访问配方部分时,才会加载它们。延迟加载默认情况下处于打开状态,因此这是默认行为。如果您将其关闭,则您已启用急切加载,该加载会加载所有配方部分及其成分。
这可能有帮助:http://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx .
关于c# - 如何使用 AutoMapper 映射食谱与成分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879303/