我使用 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);
}
天呐!