entity-framework-5 - EF5 迁移种子 AddOrUpdate 具有可为空的选择标准

标签 entity-framework-5 entity-framework-migrations

我有一个问题,过去有人可能已经找到了解决方案。我正在使用 AddOrUpdate 方法在 EF5 迁移的配置类中植入数据库。

这是域模型的快速示例:

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

然后这是我的种子方法的摘录:
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();

现在,一旦代码到达第 7 行,它就会抛出一个错误:

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



根据我的调查,这是因为 ClubId 是一个 Nullable long。

有没有办法解决?

不是主要问题 - 我只是一个完美主义者,想看看其他人是如何解决这个问题的......

谢谢,
尼克·戈洛博罗德科

最佳答案

我没有一个非常令人满意的答案,但我相信需要对 AddOrUpdate 实现进行代码更改才能解决此问题,因此我应用了一种解决方法。

简单地说,而不是使用 AddOrUpdate ,您手动执行相同的任务。例如:

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

关于entity-framework-5 - EF5 迁移种子 AddOrUpdate 具有可为空的选择标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15405875/

相关文章:

c# - AppHarbor 上的新 MVC4 应用程序出现错误 : Unable to find the requested .Net Framework Data Provider。它可能没有安装

c# - 关系的条件映射

lazy-loading - Entity Framework 5循环延迟加载导致OutOfMemoryException

c# - AddOrUpdate 未按预期工作并产生重复项

c# - EF7 在实体属性中使用 NotMapped 属性时添加迁移错误

c# - "The operation cannot be completed because the DbContext has been disposed"禁用延迟加载的异常

entity-framework - 如何撤消最后一个 Add-Migration 命令?

entity-framework - 使用 Visual Studio 2013 的 Entity Framework 迁移错误

.net-core - 无法识别术语 'Add-migration' - VS2017 和 EntityFrameworkCore

sql - 执行自定义 SQL 脚本作为 Entity Framework 迁移的一部分