Nice programing

Entity Framework 코드 첫 번째 날짜 필드 생성

nicepro 2020. 10. 13. 19:21
반응형

Entity Framework 코드 첫 번째 날짜 필드 생성


Entity Framework Code First 메서드를 사용하여 데이터베이스 테이블을 만들고 있습니다. 다음 코드 DATETIME는 데이터베이스에 DATE을 만들지 만 을 만들고 싶습니다 .

[DataType(DataType.Date)]
[DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime ReportDate { get; set; }

DATE테이블 생성 중에 유형의 열을 생성하려면 어떻게해야합니까?


David Roth의 답변의 EF6 버전은 다음과 같습니다.

public class DataTypePropertyAttributeConvention 
    : PrimitivePropertyAttributeConfigurationConvention<DataTypeAttribute>
{
    public override void Apply(ConventionPrimitivePropertyConfiguration configuration, 
        DataTypeAttribute attribute)
    {
        if (attribute.DataType == DataType.Date)
        {
            configuration.HasColumnType("Date");
        }
    }
}

이전과 같이 등록하십시오.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Conventions.Add(new DataTypePropertyAttributeConvention());
}

이것은 작업에 EF 기본 클래스를 사용한다는 점을 제외하고 Tyler Durden의 접근 방식과 동일한 결과를 제공합니다.


사용하려고 ColumnAttribute에서 System.ComponentModel.DataAnnotations(EntityFramework.dll에 정의) :

[Column(TypeName="Date")]
public DateTime ReportDate { get; set; }

나는 이것이 EF6에서 잘 작동한다는 것을 알았습니다.

데이터 유형을 지정하기위한 규칙을 만들었습니다. 이 규칙은 데이터베이스 생성의 기본 DateTime 데이터 유형을 datetime에서 datetime2로 변경합니다. 그런 다음 DataType (DataType.Date) 특성으로 장식 한 모든 속성에보다 구체적인 규칙을 적용합니다.

public class DateConvention : Convention
{
    public DateConvention()
    {
        this.Properties<DateTime>()
            .Configure(c => c.HasColumnType("datetime2").HasPrecision(3));

        this.Properties<DateTime>()
            .Where(x => x.GetCustomAttributes(false).OfType<DataTypeAttribute>()
            .Any(a => a.DataType == DataType.Date))
            .Configure(c => c.HasColumnType("date"));
    }
}

그런 다음 컨텍스트에서 규칙을 등록하십시오.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    modelBuilder.Conventions.Add(new DateConvention());
    // Additional configuration....
}

날짜 만 표시하려는 DateTime 속성에 속성을 추가합니다.

public class Participant : EntityBase
{
    public int ID { get; set; }

    [Required]
    [Display(Name = "Given Name")]
    public string GivenName { get; set; }

    [Required]
    [Display(Name = "Surname")]
    public string Surname { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Date of Birth")]
    public DateTime DateOfBirth { get; set; }
}

나는 다음을 사용한다

    [DataType(DataType.Time)]
    public TimeSpan StartTime { get; set; }

    [DataType(DataType.Time)]
    public TimeSpan EndTime { get; set; }

    [DataType(DataType.Date)]
    [Column(TypeName = "Date")]
    public DateTime StartDate { get; set; }

    [DataType(DataType.Date)]
    [Column(TypeName = "Date")]
    public DateTime EndDate { get; set; }

Entity Framework 6 및 SQL Server Express 2012-11.0.2100.60 (X64) 포함. 완벽하게 작동하며 SQL Server에서 시간 / 날짜 열 유형을 생성합니다.


를 사용하는 ColumnAttribute외에도에 대한 사용자 지정 속성 규칙을 만들 수도 있습니다 DataTypeAttribute.

public class DataTypePropertyAttributeConvention : AttributeConfigurationConvention<PropertyInfo, PrimitivePropertyConfiguration, DataTypeAttribute>
{
    public override void Apply(PropertyInfo memberInfo, PrimitivePropertyConfiguration configuration, DataTypeAttribute attribute)
    {
        if (attribute.DataType == DataType.Date)
        {
            configuration.ColumnType = "Date";
        }
    }
}

OnModelCreating 메서드에 규칙을 등록하기 만하면됩니다.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Conventions.Add(new DataTypePropertyAttributeConvention());
}

If you prefer not to decorate your classes with attributes, you can set this up in the DbContext's OnModelCreating like this:

public class DatabaseContext: DbContext
{
    // DbSet's

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // magic starts
        modelBuilder.Entity<YourEntity>()
                    .Property(e => e.ReportDate)
                    .HasColumnType("date");
        // magic ends

        // ... other bindings
    }
}

This is just an enhancement for the most up-voted answer by @LadislavMrnka on this question

if you have a lot of Date columns, then you can create custom attribute and then use it when ever you want, this will produce more clean code in the Entity classes

public class DateColumnAttribute : ColumnAttribute
{
    public DateColumnAttribute()
    {
        TypeName = "date";
    }
}

Usage

[DateColumn]
public DateTime DateProperty { get; set; }

the Best Way it using The

[DataType(DataType.Date)]
public DateTime ReportDate { get; set; }

but you must using the EntityFramework v 6.1.1

참고URL : https://stackoverflow.com/questions/5658216/entity-framework-code-first-date-field-creation

반응형