获取 class 的特定实例

Get a particular instance of a class

我已经为 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; }
    }

我想在 IngredientModel 中使用名称 属性。

在 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.AddOrUpdate 和 UnitOfMeasures.AddOrUpdate 方法中访问 UnitOfMeasureModel 类 之一。为此,在调用之前创建实例并在每个 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 不是正确的默认值,您可以更改