我知道有很多类似的问题,但没有一个对我有帮助。我有一个表'DeliveryAddresses'和'DeliveryAddressId'键(Guid类型)。它被标记为自动生成
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
但是当我试图将新记录添加到我的表中时,异常会出现:
SqlException:无法将值NULL插入列'DeliveryAddressId',表'ProjectName.dbo.DeliveryAddresses';列不允许空值。 INSERT失败。
声明已经终止。
我不知道该怎么做因为我以同样的方式向其他表添加行,所有内容看起来都一样。
public class DeliveryAddress
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid DeliveryAddressId { get; set; }
[Required(ErrorMessage = "Number of the building is required")]
public string StreetName { get; set; }
[Required(ErrorMessage = "Postcode is required")]
public string Postcode { get; set; }
[Required(ErrorMessage = "City is required")]
public string City { get; set; }
}
_
public class Product
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ProductId { get; set; }
[Display(Name = "Product")]
[Required(ErrorMessage = "Product name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Price is required")]
public double Price { get; set; }
[ForeignKey("Subcategory")]
public Guid SubcategoryId { get; set; }
public virtual Subcategory Subcategory { get; set; }
}
此代码适用于Product,不适用于DeliveryAddress
Product prod = new Product();
prod.Name = "name";
prod.Price = 10.50;
prod.SubcategoryId = _dbContext.Subcategories.FirstOrDefault(s => s.SubcategoryId != null).SubcategoryId;
_dbContext.Products.Add(prod);
_dbContext.SaveChanges();
DeliveryAddress add = new DeliveryAddress();
add.City = "City";
add.StreetName = "Street";
add.Postcode = "55555";
_dbContext.DeliveryAddresses.Add(add);
_dbContext.SaveChanges();
即使使用add.DeliveryAddressId = Guid.NewGuid()
也无效。
我只能告诉你:当我错误地创建模型时,我将这个类命名为“DelieveryAddress”(额外的“e”),但它在下一次迁移中已经修复,也许是关于它的?