繁体   English   中英

SQL服务器使用实体框架核心3.1时指定列类型

[英]Specifying the column type when using entity framework core 3.1 with SQL Server

考虑这个简单的 class,我将在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 选项,还是有其他方法?

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

[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 对于DateTime System应该是您需要的唯一namespace

这个问题基本上有两种可能性。 一种是使用前面回答中提到的属性或者使用EF core提供的fluent API。

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

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

基本上所需的代码是数据库上下文中的以下代码

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM