实体框架为NOT NULL列生成值,其默认值在db中定义

Kas*_*hif 6 c# entity-framework-4

嗨,我有一个表客户.表中的一列是DateCreated.此列是NOT NULL但在db中为此列定义了默认值.

当我Customer从我的代码中使用EF4 添加新内容时.

var customer = new Customer();
customer.CustomerName = "Hello";                
customer.Email = "hello@ello.com";
// Watch out commented out.
//customer.DateCreated = DateTime.Now;
context.AddToCustomers(customer);
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

上面的代码生成以下查询.

exec sp_executesql N'insert [dbo].[Customers]([CustomerName], 
[Email], [Phone], [DateCreated], [DateUpdated])
values (@0, @1, null, @2, null)
select [CustomerId]
from [dbo].[Customers]
where @@ROWCOUNT > 0 and [CustomerId] = scope_identity()
',N'@0 varchar(100),@1 varchar(100),@2 datetime2(7)
',@0='Hello',@1='hello@ello.com',@2='0001-01-01 00:00:00'
Run Code Online (Sandbox Code Playgroud)

并抛出错误

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Run Code Online (Sandbox Code Playgroud)

你能告诉我在db级别有默认值的NOT NULL列怎么不具有EF生成的值?

D B:

DateCreated DATETIME NOT NULL
Run Code Online (Sandbox Code Playgroud)

EF中的DateCreated属性:

  • 可空:错误
  • Getter/Setter:公开
  • 类型: DateTime
  • DefaultValue:

谢谢.

TyC*_*obb 7

根据我对EF(最小)的了解,它不会从架构中获取默认值.您插入行和列的事实被标记为NOT NULL,这意味着EF认为它应该为该列插入一个恰好具有DateTime.MinValue值的值.

您可能需要在实体构造函数中强制使用自己的值,或者创建一些工厂方法.

EF中的表设计器的属性页上是否有任何内容可以指定默认值?


Jos*_*zca 5

你得跟ORM说这个属性是数据库生成的。对于上一个示例中 Customer 类中的示例,以下代码应该可以工作。

public class Customer{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]//The database generates a value when a row is inserted. 
    public int CustomerId { get; set; }

    public string CustomerName { get; set; }

    public string Email { get; set; }

    public string Phone { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)] //The database generates a value when a row is inserted or updated.
    public DateTime DateCreated { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.IComputed)]//The database generates a value when a row is inserted or updated.
    public DateTime DateUpdated { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

不要忘记添加

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
Run Code Online (Sandbox Code Playgroud)

对于主键,由于我不知道的原因,当您在模型类中至少使用一次 DatabaseGeneratedAttribute 的注释时,您必须指定生成的选项方法。当我使用它们时,出现错误,因为 ORM 试图在查询语句中插入键,而不是让数据库生成它们。

有三个数据库生成选项

  • Computed:数据库在插入或更新行时生成一个值。
  • Identity:数据库在插入一行时生成一个值。
  • :数据库不生成值。

您可以在此处找到文档数据库生成的选项