c# - Entity Framework - 以多列索引作为标识符的种子 AddOrUpdate

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

我正在尝试使用 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
    });

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

最佳答案

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

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
    });

关于c# - Entity Framework - 以多列索引作为标识符的种子 AddOrUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452497/

相关文章:

sql - 如何添加代码初始化sql数据库

c# - 根据 json 值路由到不同的操作

c# - 带委托(delegate)的 Linq 查询不更新变量

asp.net - 为什么 "SingleOrDefault"在DB中有数据的情况下第二次执行时返回null?

c# - 强制 ASP.NET Core Entity Framework Core 中的继承类到专用 MySQL 表

entity-framework - 使用 Entity Framework 6 迁移创建索引

c# - WPF:如何实现通用窗口?

C# 继承构造函数子和父 ??

entity-framework - 在 Entity Framework 中使用 EntityDataSource 与 ObjectDataSource 的优缺点?

c# - 编译查询错误 : there is no implicit conversion from entities to 'System. Data.Objects.ObjectContext