获取类的特定实例

本文关键字:实例 获取 | 更新日期: 2023-09-27 18:17:11

我已经为UnitOfMeasure (UOM)创建了一个模型,并为配料创建了一个模型,我想在其中使用UOM为配料输入一个默认的UOM。

 public class IngredientModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public UnitOfMeasureModel DefaultUOM { get; set; }
    }
 public class UnitOfMeasureModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Abbreviation { get; set; }
    }

我想在配料模型中使用Name属性。

在configure.cs中,我放置了以下代码来为数据库创建一些默认数据:

    protected override void Seed(RecipeApplication.Models.RecipeApplicationDb context)
    {
        if (!context.UnitOfMeasures.Any())
        {
            context.UnitOfMeasures.AddOrUpdate(
                u => u.Id,
                new UnitOfMeasureModel { Name = "Gram", Abbreviation = "g" },
                new UnitOfMeasureModel { Name = "Kilogram", Abbreviation = "kg"},
                new UnitOfMeasureModel { Name = "Milligram", Abbreviation = "mg" }
                );
        }
        if (!context.Ingredients.Any())
        {
            context.Ingredients.AddOrUpdate(
                i => i.Id,
                new IngredientModel { Name = "Italiaanse Ham", DefaultUOM = 
                );
        }
    }

我没有在默认的UOM中输入任何东西,因为这就是我被卡住的地方。

有人能帮我解决这个问题吗?

获取类的特定实例

我假设你只是想能够在两个UnitOfMeasures中访问一个UnitOfMeasureModel类。AddOrUpdate和UnitOfMeasures。AddOrUpdate方法。为此,在调用之前创建实例,并在每个AddOrUpdate方法中使用相同的实例,如下.....

protected override void Seed(RecipeApplication.Models.RecipeApplicationDb context)
{
    var defaultUOM = new UnitOfMeasureModel { Name = "Gram", Abbreviation = "g" };
    if (!context.UnitOfMeasures.Any())
    {
        context.UnitOfMeasures.AddOrUpdate(
            u => u.Id,
            defaultUOM,
            new UnitOfMeasureModel { Name = "Kilogram", Abbreviation = "kg"},
            new UnitOfMeasureModel { Name = "Milligram", Abbreviation = "mg" }
            );
    }
    if (!context.Ingredients.Any())
    {
        context.Ingredients.AddOrUpdate(
            i => i.Id,
            new IngredientModel { Name = "Italiaanse Ham", DefaultUOM = defaultUOM
            );
    }
}

显然你可以改变如果gram不是正确的默认值