【问题标题】:how to string field be unique mvc 5 asp.net [closed]如何字符串字段是唯一的mvc 5 asp.net [关闭]
【发布时间】:2015-03-26 09:24:46
【问题描述】:
public class Sport
{

    public int SportID { get; set; }

    [Required(ErrorMessage = "The Name field is required.")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    [StringLength(50, MinimumLength = 3)]
    public string Name { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Start Date")]
    public DateTime StartDate { get; set; }

    [Column(TypeName = "money")]
    public decimal Price { get; set; }

    public int? InstructorID { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }

    public virtual ICollection<Instructor> Instructors { get; set; }
    public virtual ICollection<Group> Groups { get; set; }

}

此表中的键是 SportID。 我可以创建更多同名的运动,但我不喜欢这样

我的运动名称如何才能唯一?请帮我。谢谢

【问题讨论】:

  • I can create a more sports with a same name, but i don't like this 这是什么意思?在数据库中创建它们?这里需要更多信息。

标签: c# asp.net-mvc unique


【解决方案1】:

您正在寻找Index 数据注释。文档here

[Required(ErrorMessage = "The Name field is required.")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[StringLength(50, MinimumLength = 3)]
[Index]
public string Name { get; set; }

【讨论】:

  • 在 Entity Framework 6.1 中引入了 Index 属性。如果您使用的是早期版本,则本节中的信息不适用。
【解决方案2】:

SportID 将是唯一的(在大多数情况下 - 从数据库中获取主键)

Wrt SportName 是唯一的,你必须采取预防措施(地点验证规则 - 客户端/服务器端)我会推荐 MVC 中的远程验证

Remote Validation

Remote Validation Video

【讨论】:

    猜你喜欢
    • 2014-02-12
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    相关资源
    最近更新 更多