简体   繁体   中英

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

Consider this simple class, that I will use for one of my Domain objects with 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; }
    }
}

Having a database background, I do not want to use the default type of nvarchar(max) as the column type for string values in my database (SQL Server). How do I specify the column types to be used by EF when creating the table?

Also, do I have to include the whole SYSTEM Namespace just to be able to have the DateTime option available to me for my CreatedDate field or is there another way?

You should be able to add an attribute on each string value which will look like this

[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.....

Or you could use [StringLength(50, MinimumLength = 5)]

To use [MaxLength()] you will need System.Collections.Generic . For DateTime System should be the only namespace that you need.

Basically there are two possibilities for this problem. The one is to use the attributes mentioned in the previous answer or to use the fluent API provided by EF core.

Fluent API allows you to configure precisely your database properties.

More info can be found in the documentation

Basically the required code is the following in the database context

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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