使用Entity Framework 5.0进行数据注释(数据库优先)

Mit*_*all 22 c# entity-framework data-annotations entity-framework-5

如果我使用Entity Framework(v5.0)数据库第一种方法,那么使用数据注释进行验证的最佳方法是什么?

这是我的Entity Framework创建的部分类:

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.ComponentModel.DataAnnotations;

namespace ACore
{
    using System;
    using System.Collections.Generic;

    public partial class PayrollMarkup_State
    {
        [UIHint("StatesEditor")] // <-- I added this line but it will be overwritten
        public string State { get; set; }
        public Nullable<float> MaintenancePercentage { get; set; }
        public Nullable<float> OfficePercentage { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过这个没有成功......

实体框架生成的文件:'PayrollMarkup_State.cs'

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.ComponentModel.DataAnnotations;

namespace ACore
{
    using System;
    using System.Collections.Generic;

    public partial class PayrollMarkup_State
    {
        public string State { get; set; }
        public Nullable<float> MaintenancePercentage { get; set; }
        public Nullable<float> OfficePercentage { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我在另一个目录中创建了这个文件:'PayrollMarkup_state.cs'

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace ACore.Models
{
    [MetadataType(typeof(PayrollMarkupMetadata))]
    public partial class PayrollMarkup_State
    {
    }

    public class PayrollMarkupMetadata
    {
        [UIHint("StatesEditor")]
        public string State; // Has to have the same type and name as your model
    }
}
Run Code Online (Sandbox Code Playgroud)

Gal*_*boy 23

虽然这有点痛苦,但您需要创建一个类来用作MetadataType模型类.

[MetadataType(typeof(PayrollMarkupMetadata))
public partial class PayrollMarkup_State
{
  ...
}

public class PayrollMarkupMetadata
{
    [UIHint("StatesEditor")]
    public string State; // Has to have the same type and name as your model
    // etc.
}
Run Code Online (Sandbox Code Playgroud)

  • @JYL是的,它不会看它是一个字段还是属性,它只是一个间接机制."在这个类型和名称的其他类中找到这个东西,并将这些属性应用于它." (2认同)