在模型中唯一的财产

在模型中唯一的财产

本文介绍了ASP.NET MVC 4,EF5,在模型中唯一的财产 - 最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET MVC 4,EF5, code首先,SQL Server 2012的前preSS

ASP.NET MVC 4, EF5, Code First, SQL Server 2012 Express

什么是执行模型中的独特价值的最佳实践?我有一个具有URL属性,应该是每一个地方独特的一类的地方。

What is best practice to enforce a unique value in a model? I have a places class that has a 'url' property that should be unique for every place.

public class Place
{
      [ScaffoldColumn(false)]
      public virtual int PlaceID { get; set; }

      [DisplayName("Date Added")]
      public virtual DateTime DateAdded { get; set; }

      [Required(ErrorMessage = "Place Name is required")]
      [StringLength(100)]
      public virtual string Name { get; set; }

      public virtual string URL { get; set; }
};

为什么没有只是一个[独特]数据注解可以在其上放置?

Why isn't there just a [Unique] data annotation you can place on it?

我看到的这个1或2的讨论,但没有最佳实践的说法。使用code首先你能以某种方式告诉数据库设置在球场上的唯一约束数据库?

I have seen 1 or 2 discussions on this, but no talk of best practice. Using Code First can you somehow tell the database to set a unique constraint on the field in the database?

什么是最简单的方式 - 什么是最好的做法?

What is easiest way - and what is best practice?

推荐答案

由于疯狂的,因为它听起来最好的做法现在是为不可以内置的使用验证,而使用的。然后,code会很容易阅读和超级维护,因为验证将在单独的类意味着更少的面条code进行管理。

As crazy as it might sound the best practice nowadays is to not use built-in validation and instead use FluentValidation. Then the code will be very easy to read and super-maintainable since validation will be managed on separate class meaning less spaghetti code.

你正在试图达到什么伪的例子。

Pseudo-example of what you are trying to achieve.

[Validator(typeof(PlaceValidator))]
class Place
{
    public int Id { get; set; }
    public DateTime DateAdded { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }
}

public class PlaceValidator : AbstractValidator<Place>
{
    public PlaceValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Place Name is required").Length(0, 100);
        RuleFor(x => x.Url).Must(BeUniqueUrl).WithMessage("Url already exists");
    }

    private bool BeUniqueUrl(string url)
    {
        return new DataContext().Places.FirstOrDefault(x => x.Url == url) == null
    }
}

这篇关于ASP.NET MVC 4,EF5,在模型中唯一的财产 - 最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 15:12