entity-framework - 类型 Nullable<Int32> 和 Int32 之间未定义二元运算符 Equal

标签 entity-framework asp.net-mvc-4 model

我有以下模型:

public class DeviceConfigurationModel
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Device Configuration Id")]
    public int DeviceConfigurationId { get; set; }

    [Required]
    [Display(Name = "Device Profile Name")]
    [StringLength(50)]
    public string ProfileName { get; set; }

    [StringLength(50)]
    public string SERV { get; set; }

    [StringLength(50)]
    public string IPAD { get; set; }

    public Nullable<int> PORT { get; set; }

    [Required]
    [Display(Name = "Is Active")]
    public bool IsActive { get; set; }

    [Required]
    [Display(Name = "Date Created")]
    public DateTime DateCreated { get; set; }
}

我使用命令 update-database 通过包管理器控制台播种以及 configuration.cs 中用于迁移的以下代码:
    context.DeviceConfigurations.AddOrUpdate(
         d => new { d.ProfileName, d.IPAD, d.PORT, d.IsActive },
              new DeviceConfigurationModel { ProfileName = "FMG Default Gateway", IPAD = "77.86.28.50", PORT = (int?)90, IsActive = true  }
    );

但是,每当它尝试运行这行代码时,我都会在控制台中收到以下错误:
The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'.

有谁知道如何解决这个问题,我曾尝试寻找答案,但大多数解决方案是使其不可为空并只接受零,但我不想这样做,因为我需要使用零值一些领域

更新

进一步研究后,我将范围缩小到运行更新的内容列表:如果我省略了 d.PORT从线
d => new { d.ProfileName, d.IPAD, d.PORT, d.IsActive }

然后更新工作正常。当然必须有一种方法可以让更新也查看这个字段,否则如果它甚至不能处理像可为空的 int 这样的简单事情,那么使用 mvc 似乎是非常无用的

最佳答案

尝试使用 Fluent API 将字段显式设置为 Optional:

 public class YourContext : DbContext
    {
        public DbSet<DeviceConfigurationModel> DeviceConfigurations { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<DeviceConfigurationModel>().Property(x => x.PORT).IsOptional();
        }
    }

这应该强制类型可以为空。

出于某种原因,将您的属性(property)声明为 int?而不是 Nullable<int>将导致 EF 也按预期生成您的属性(property)。

关于entity-framework - 类型 Nullable<Int32> 和 Int32 之间未定义二元运算符 Equal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16818382/

相关文章:

javascript - 在 extjs 的存储中动态设置字段或 getCount() 在模型中给出 0

entity-framework - Lambda 表达式 Where on navigation property

c# - 并行使用 DbContext

c# - EF6 可选 1 :1 include not working

javascript - 我正在尝试使用 mvc4 捆绑功能缩小 javascript 文件

asp.net-mvc-4 - 所以我们已经让 MEF 与 MVC4 一起工作,基于约定的模型怎么样?

asp.net-mvc - 通过生成 Entity Framework 脚手架 API Controller 错误使用 Web API

c# - MVC 4 在区域内路由 "finding" Controller

php - CakePHP、电子邮件模型和电子邮件组件。我做过蠢事

php - cakephp saveall 如果在保存之前返回 false 则中断