一组EF类的单一唯一属性

时间:2012-02-28 09:14:50

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

我有一堆由EF(简化)生成的类:

public class Country
{
    [UniqueCountry(ErrorMessage = "Record previously added")]
    public String COUNTRY { get; set; }
}

public class Region
{
    [UniqueRegion(ErrorMessage = "Record previously added")]
    public String REGION { get; set; }
}

public class City
{
    [UniqueCity(ErrorMessage = "Record previously added")]
    public String CITY { get; set; }
}

然后,我有3个单独的视图来创建或编辑这些实体。 我想确保用户输入的值是唯一的,如果不是,请向用户提供错误消息。这样我想使用DataAnnotation属性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class UniqueCountryAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var model = value as string;
        using (var db = new myEntities())
        {
            return !db.Country.Any(p => p.COUNTRY.ToLower() == model.ToLower());
        }
    }
}

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class UniqueRegionAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var model = value as string;
        using (var db = new myEntities())
        {
            return !db.Region.Any(p => p.REGION.ToLower() == model.ToLower());
        }
    }
}

有没有办法避免为每个类创建一个唯一的属性,并避免创建怪物切换?

它们之间的唯一区别是表名和上下文的列名。

0 个答案:

没有答案