的Int32&gt;在二元运算符平等是不是可空类型℃之间定义;和的Int32 [英] The binary operator Equal is not defined between type Nullable<Int32> and Int32
问题描述
我有以下型号:
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; }
}
这是我通过包管理器控制台命令更新数据库
,并在configuration.cs为迁移以下code种子:
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 }
);
然而,当它试图运行此行code的我在控制台中出现以下错误:
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
更新
打过这个进一步,我已经缩小下来事物的更新上运行列表:如果我在 d.PORT
从线漏下
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 }
则更新工作正常。当然,必须有一个方法,使更新还看这个领域,否则似乎使用MVC是pretty无用的,如果它甚至不能处理像一个可空INT一件简单的事情。
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
推荐答案
尝试将字段设置为可选的明确使用流利的API:
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();
}
}
这应该强制类型为空。
由于某些原因,宣告你的财产为 INT
而不是可空&LT; INT&GT;
将导致EF产生你的财产如预期好。
For some reason, declaring your property as int?
instead of Nullable<int>
will cause EF to generate your property as expected as well.
这篇关于的Int32&gt;在二元运算符平等是不是可空类型℃之间定义;和的Int32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!