在将实体框架核心 3.1 与 SQL Server 配合使用时指定列类型



请考虑这个简单的类,我将在EF Core 3.1中将其用于我的一个域对象:

using System;
namespace Blah.Domain
{
public class Response
{
public int Id { get; set; }
public string FullResponseText { get; set; }
public string HttpResponseCode { get; set; }
public string TransactionId { get; set; }
public string TransactionType { get; set; }
public DateTime CreatedDate { get; set; }
}
}

有了数据库背景,我不想使用默认类型的 nvarchar(max( 作为我的数据库 (SQL Server( 中字符串值的列类型。 如何指定 EF 在创建表时要使用的列类型?

另外,我是否必须包含整个SYSTEM命名空间才能为我的 CreatedDate 字段提供 DateTime 选项,还是有其他方法?

基本上这个问题有两种可能性。一种是使用上一个答案中提到的属性或使用 EF 核心提供的流畅 API。

Fluent API 允许您精确配置数据库属性。

更多信息可以在文档中找到

基本上,数据库上下文中所需的代码如下

modelBuilder.Entity<Address>()
.Property(a => a.StateProvince).HasColumnType("varchar(20)");

您应该能够在每个字符串值上添加一个属性,如下所示

[MaxLength(50)] //Whatever int value in `maxlength` will be the size in sql
public string FullResponseText { get; set; }
[MaxLength(255)]
public string HttpResponseCode { get; set; }
etc.....

或者你可以使用[StringLength(50, MinimumLength = 5)]

要使用[MaxLength()]您将需要System.Collections.Generic。因为DateTimeSystem应该是你唯一需要的namespace

最新更新