Entity Framework - Seed AddOrUpdate with multi column index as identifier
Asked Answered
U

1

10

I am trying to seed a database using the context.AddOrUpdate method, but the problem is that I need to make the inserted data unique based on a multi column index.

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

Currently I AddOrUpdate based on the Name of the climbing grade, but now I am at a point where I need to insert duplicate names.

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

Is it possible to compare multi column indexes when I insert seed data?

Unscrupulous answered 17/2, 2016 at 9:22 Comment(2)
What do you mean by "is it possible to compare...?" What do you exactly want to do? Do you want to only keep some of the possible repeated values?Xanthippe
I want to use the multi column index as a reference if the data set already exists in the database. e.g.: .AddOrUpdate(grade => grade.Name == existing.Name && grade.GradeType == existing.GradeType)Unscrupulous
H
12

You need to use anonymous type for specifying multiple columns. This also works without specifying the indicies.

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
    });
Hashim answered 17/2, 2016 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.