Mike
Mike

Reputation: 1

EntityFramework DataAnnotations validation doesnt work

I've used EF Power Tools to auto generate my models from an existing database. Im using DataAnnotations to perform required validation, which works for most part except when validating properties that have foreign key relationship with other tables (one to many, etc..). What do I need to do in order to accomplish the validation of these properties?

In the below code, I'm trying to make DistributorId property a required field.

 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; }

}

Mapping class

 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!

Upvotes: 0

Views: 232

Answers (1)

Display Name
Display Name

Reputation: 4732

This is very simply because Name is a string (which is nullable), while DistributorId is an int (not nullable). That means that DistributorId always exists (although can be not the value you looking for, but still [Required] validation is satisfied.

What you probably want to change is to

  • either replace [Required] with something that will validate the actual value [Range] is great example here.
  • or have DistributorId as string converting it to int before writing to the database.

Hope this helps

Upvotes: 2

Related Questions