【发布时间】:2018-07-11 15:57:42
【问题描述】:
当我使用Update-Database 时,它通常运行良好,并且我在 SQL 端看到了我的更改。在我创建模型的时候,所有属性都使用了Required,但是去掉这个注解后,映射的列还是not null。我已经通过添加和删除列来测试我的迁移设置,这很好。
我的模型是这样的:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Company.Employees {
[Serializable]
[Table("EmployeeRecords")]
public class EmployeeRecords {
[Key]
[Required]
public Guid EmployeeID { get; set; }
[Required]
[Display(Name = "Date Submitted")]
public DateTime DateSubmitted { get; set; }
[Display(Name = "Date Processed")]
public DateTime? DateProcessed { get; set; }
[Required]
[Display(Name = "Submitted By")]
public string SubmittedBy { get; set; }
[Required]
[Display(Name = "Employees")]
public Int16 Employees { get; set; }
[Required]
[Display(Name = "Total Wages")]
public decimal TotalWages { get; set; }
[Required]
[Display(Name = "Total Benefits")]
public decimal TotalBenefits { get; set; }
public List<EmployerReference> EmployerReferences { get; set; }
}
}
您会看到属性DateProcessed 不是[Required]。但 EF 没有看到这一点。
我还使用其他数据注释进行了测试。我添加了[MaxLength(450)],然后运行了更新数据库。这行得通,在 SQL 中,映射列更改为 VARCHAR(450)
我可能会走得很远,这是我第一个使用代码优先的应用程序。如果需要更多信息,请告诉我。谢谢!!
编辑:
我刚刚尝试使用这样的 Fluent API:
modelBuilder.Entity<RemittanceBatch>().Property(m => m.DateProcessed).IsOptional();
base.OnModelCreating(modelBuilder);
这也没用。
编辑 2:
它允许我将DateSubmitted 字段设为可为空。但不允许我将 DateProcessed 字段设为可为空。这里有什么区别……嗯
【问题讨论】:
-
我认为您需要使用
[Column()]而不是[Display()]。 docs.microsoft.com/en-us/ef/core/modeling/relational/… -
感谢您的链接。我不知道这存在。我刚才确实尝试添加这个并且没有任何变化。似乎列自动映射得很好
-
看看你的迁移
Up()和Down()看看它在做什么。 -
我在做研究的时候遇到了一些关于 Up() 和 Down() 的东西。我会进一步调查。
-
方法是空的,一方面哈哈
标签: c# sql asp.net-mvc ef-code-first