【问题标题】:Specifying the column type when using entity framework core 3.1 with SQL Server将实体框架核心 3.1 与 SQL Server 一起使用时指定列类型
【发布时间】:2020-09-28 21:25:58
【问题描述】:

考虑这个简单的类,我将在 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; }
    }
}

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

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

【问题讨论】:

    标签: c# sql-server .net-core entity-framework-core


    【解决方案1】:

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

    [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

    【讨论】:

    • 然而,为了创建.net core 项目,还有很多命名空间仍然需要其他功能。 System 无论如何都是必需的,我很确定,它确实包括基本的string,int,double 等类,DateTime 会在没有System 的情况下抛出错误,但是你要具体并使用system.DateTime 只包括DateTime
    【解决方案2】:

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

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

    更多信息可以在documentation找到

    在数据库上下文中基本上需要的代码如下

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      相关资源
      最近更新 更多