【问题标题】:Entity Framework - Seed AddOrUpdate with multi column index as identifier实体框架 - 以多列索引作为标识符的种子 AddOrUpdate
【发布时间】:2016-05-28 21:49:03
【问题描述】:

我正在尝试使用context.AddOrUpdate 方法为数据库播种,但问题是我需要根据多列索引使插入的数据唯一。

[Table("climbing_grades")]
public class ClimbingGrade : EntityBase
{
    /// <summary>
    /// The name of the climbing grade, e.g.: 7a, VII, etc.
    /// </summary>
    [Index("IX_Name_GradeType", 1, IsUnique = true)]
    public string Name { get; set; }

    /// <summary>
    /// Tries to display the average difficulty of the described grade.
    /// Matching the different grades can be difficult because its always
    /// a subjective rating and there exists no norm on converting grades.
    /// </summary>
    public double Difficulty { get; set; }

    /// <summary>
    /// The type of the grade. Will be the respective region rating.
    /// e.g.: UUIA for most oft europe, YSD for USA, etc.
    /// </summary>
    [Index("IX_Name_GradeType", 2, IsUnique = true)]
    public ClimbingGradeType GradeType { get; set; }
}

目前我AddOrUpdate基于攀登等级的Name,但现在我需要插入重复名称。

context.ClimbingGrades.AddOrUpdate(grade => /* Compare multi column index here?*/,
    new ClimbingGrade
    {
        Name = "5a",
        Difficulty = 4.75,
        GradeType = ClimbingGradeType.FontainebleauBloc
    },
    new ClimbingGrade
    {
        Name = "5a",
        Difficulty = 4.25,
        GradeType = ClimbingGradeType.FontainebleauTraverse
    });

插入种子数据时是否可以比较多列索引?

【问题讨论】:

  • 您所说的“是否可以比较...?”是什么意思?你到底想做什么?你想只保留一些可能的重复值吗?
  • 如果数据库中已经存在数据集,我想使用多列索引作为参考。例如:.AddOrUpdate(grade =&gt; grade.Name == existing.Name &amp;&amp; grade.GradeType == existing.GradeType)

标签: c# entity-framework ef-code-first entity-framework-migrations seeding


【解决方案1】:

您需要使用匿名类型来指定多个列。这也适用于不指定索引的情况。

context.ClimbingGrades.AddOrUpdate(grade => new { grade.Name, grade.GradeType },
    new ClimbingGrade
    {
        Name = "5a",
        Difficulty = 4.75,
        GradeType = ClimbingGradeType.FontainebleauBloc
    },
    new ClimbingGrade
    {
        Name = "5a",
        Difficulty = 4.25,
        GradeType = ClimbingGradeType.FontainebleauTraverse
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    相关资源
    最近更新 更多