简体   繁体   English

Asp.net MVC,使用弱实体验证唯一行

[英]Asp.net MVC, validation of unique rows with weak entities

So I have an entity EmployeeRegion 所以我有一个实体EmployeeRegion

EmployeeRegion is a weak entity with a composite key from the tables Region and Employee . EmployeeRegion是一个弱实体,具有来自RegionEmployee表的组合键。

I have an employee profile where they can add themselves to a region. 我有一个员工资料,他们可以将自己添加到区域中。 They get a drop down with the regions 他们随地区而下降

在此处输入图片说明

I'm doing a pass where I get everything in the model compliant with the data validation stuff that's built in to Asp.net MVC. 我正在通过,使模型中的所有内容都与Asp.net MVC内置的数据验证内容兼容。 This is great because the validation (using annotations) shows really great error messages to the end user. 这很棒,因为验证(使用批注)向最终用户显示了非常好的错误消息。

How, using annotations, can I validate that a composite key is unique, and if not, show an error message? 如何使用注释来验证组合键是唯一的,如果不是,则显示错误消息?

Basically, you just need: 基本上,您只需要:

public class EmployeeRegion
{
    [Key, Column(Order = 1)]
    public int EmployeeId { get; set; }
    public virtual Employee Employee { get; set; }

    [Key, Column(Order = 2)]
    public int RegionId { get; set; }
    public virtual Region Region { get; set; }
}

In other words, the part you're missing is [Key, Column(Order = N)] . 换句话说,您缺少的部分是[Key, Column(Order = N)] This makes the ids an actual composite key, which out of the box won't allow duplicates. 这使id成为实际的组合键,开箱即用将不允许重复。

However, all this does is make the API more difficult for working with this M2M relationship. 但是,所有这些操作使API更加难以使用这种M2M关系。 If the only data in the table is the keys and there's no payload of additional data needed for the relationship, then you should get rid of this entity and simply let EF handle the relationship: 如果表中唯一的数据是键,并且该关系没有其他数据的有效负载,那么您应该摆脱此实体,只需让EF处理该关系即可:

public class Employee
{
    ...

    public virtual ICollection<Region> Regions { get; set; }
}

public class Region
{
    ...

    public virtual ICollection<Employee> Employees { get; set; }
}

Behind the scenes, EF will create a table similar to what you have with EmployeeRegion , but you won't be responsible for managing that, and things like ensuring unique relationships will be baked in. This also buys you a much easier API to work with. 在幕后,EF将创建一个与EmployeeRegion类似的表,但是您将不负责管理该表,并且将确保加入独特的关系(例如,确保建立独特的关系)。这也使您可以更轻松地使用API 。 For example. 例如。 To get all the employees for a region, currently, you'd have to do something like: 要获得某个地区的所有员工,当前,您必须执行以下操作:

dbo.EmployeeRegions.Where(m => m.Region.Id == regionId).Select(m => m.Employee)

Whereas, by allowing EF to handle it, you can just do: 而通过允许EF处理它,您可以执行以下操作:

region.Employees

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM