Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF5 Migrations Seed AddOrUpdate with a nullable selection criteria

I have a question to which someone may have found a solution in the past. I'm seeding the database in the Configuration class of EF5 migrations, using the AddOrUpdate method.

Here's the quick example of the domain model:

 public class Club
{
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }
}

public class Court
{
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }

    public virtual long? ClubId { get; set; }
    public virtual Club Club { get; set; }
}

Then here is an extract from my seed method:

Club cb = new Club { Name = "Test Club 1" };
context.Set<Club>().AddOrUpdate(m=>m.Name, cb);
context.SaveChanges();

Court crt1 = new Court { ClubId = cb.Id, Name = "Court 1" };
Court crt2 = new Court { ClubId = cb.Id, Name = "Court 2" };
context.Set<Court>().AddOrUpdate(m => new { m.Name, m.ClubId }, crt1, crt2);
context.SaveChanges();

Now, once the code reaches line number 7, it throws an error:

The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int64]' and 'System.Int64'.

From my investigation it's due to the fact that ClubId is a Nullable long.

Is there any way around this?

Not a major issue - I'm just a perfectionist, and would like to see how others may have solved this...

Thanks, Nick Goloborodko

like image 587
Nick Goloborodko Avatar asked Mar 14 '13 09:03

Nick Goloborodko


1 Answers

I don't have a very satisfactory answer, but I believe that there would need to be a code change to the AddOrUpdate implementation to fix this so I have applied a workaround.

Simply put, rather than use AddOrUpdate, you do the same task manually. For example:

private void AddOrUpdateCourt(long id, string name, string someOtherPropertyValue)
{
    var court = _context.Set<Court>().SingleOrDefault(c => c.Id = id && c.Name = name);
    if(court == null)
    {
        _context.Set<Court>().Add(new Court
        {
            ClubId=id, 
            Name=name, 
            SomeOtherProperty = someOtherPropertyValue
        });
    }
    else
    {
        court.SomeOtherProperty = someOtherPropertyValue;
    }
}
like image 83
Josh Gallagher Avatar answered Jun 24 '23 17:06

Josh Gallagher