The binary operator Equal is not defined between type Nullable and Int32

asp.net-mvc-4 entity-framework model

Question

I have the following 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; }
}

which I seed through the package manager console with the command update-database and the following code in the configuration.cs for the migration:

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

However, whenever it tries to run this line of code I get the following error in the console:

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

does anyone know how to fix this problem, I have tried looking for answers but most of the solutions are to make it non-nullable and just accept a zero but I don't want to do this as I need to use a zero value for some of the fields

UPDATE

Having played with this further, I have narrowed this down to the list of things the update is run on: if I leave out the d.PORT from the line

d => new { d.ProfileName, d.IPAD, d.PORT, d.IsActive }

then the update works fine. Surely there must be a way to make the update also look at this field otherwise it seems that using mvc is pretty useless if it can't even handle a simple thing like a nullable int

1
11
5/30/2013 9:10:02 AM

Accepted Answer

Try setting the field to Optional explicitly using the Fluent API:

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

This should force the type to be nullable.

For some reason, declaring your property as int? instead of Nullable<int> will cause EF to generate your property as expected as well.

2
6/5/2013 2:03:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow