【问题标题】:EntityFramework DataAnnotations validation doesnt work实体框架 DataAnnotations 验证不起作用
【发布时间】:2012-08-21 13:59:21
【问题描述】:

我使用 EF Power Tools 从现有数据库自动生成模型。我使用 DataAnnotations 来执行所需的验证,这在大多数情况下都有效,除了验证与其他表具有外键关系的属性(一对多等)时。为了完成这些属性的验证,我需要做什么?

在下面的代码中,我试图将 DistributorId 属性设为必填字段。

 public class Event
{
    public Event()


    public int EventId { get; set; }
    [Remote ("CheckDuplicateEventName","Event",AdditionalFields="InsertMode")]
    [Required(ErrorMessage = "Event Name is required.")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Distributor is required.")]
    public int DistributorId { get; set; }

    public virtual Distributor Distributor { get; set; }

}

映射类

 public EventMap()
    {
        // Primary Key
        this.HasKey(t => t.EventId);

        // Properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(256);

        // Table & Column Mappings
        this.ToTable("Events");
        this.Property(t => t.EventId).HasColumnName("EventId");
        this.Property(t => t.Name).HasColumnName("Name");
        this.Property(t => t.DistributorId).HasColumnName("DistributorId");

        // Relationships
        this.HasRequired(t => t.Distributor)
            .WithMany(t => t.Events)
            .HasForeignKey(d => d.DistributorId);


    }

Tnx!

【问题讨论】:

  • 您是否要验证相关记录是否存在?我不认为你能做到这一点,你必须依靠数据库为你做到这一点。
  • 我只是想将 DistributorId 验证为表单上的必填字段。 DistributorId 的验证永远不会启动,而 Name 则可以正常工作。
  • 是的,我认为您不能使用数据注释来做到这一点,因为 EF 不会将关系 id 字段视为与普通数据库字段相同。或者,您可以在数据上下文中覆盖 SaveChanges 方法并自己进行验证。

标签: asp.net-mvc entity-framework data-annotations


【解决方案1】:

这很简单,因为Namestring(可以为空),而DistributorIdint(不可为空)。这意味着DistributorId 始终存在(虽然可能不是您要查找的值,但仍然满足[Required] 验证。

你可能想要改变的是

  • 要么替换 [Required] 以验证实际值 [Range] 是一个很好的例子。
  • 或将DistributorId 作为字符串在写入数据库之前将其转换为int。

希望对你有帮助

【讨论】:

  • 那个,或者对于一些非常基本的验证,对 int 值进行某种范围验证。
猜你喜欢
  • 1970-01-01
  • 2010-12-17
  • 2010-09-16
  • 1970-01-01
  • 2014-08-24
  • 2011-04-28
  • 2017-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多