简体   繁体   English

数据库中不需要的属性的必需属性

[英]Required attribute for property that is not required in the database

I have a form, where some fields are mandatory.我有一个表格,其中一些字段是必填的。 A few of the mandatory fields have not always been mandatory, hence there are null values in the database.一些必填字段并不总是必填的,因此数据库中有 null 个值。

If I add [Required] for the property, I will get a SqlNullValueException, because there are null values in the database.如果我为属性添加 [Required],我将得到一个 SqlNullValueException,因为数据库中有 null 个值。

What is the best practice to get a field to behave as if it had a [Required] attribute?让字段表现得好像它具有 [Required] 属性的最佳做法是什么?

[Required]
public string? foo { get; set; }

You're a bit light on context here, but I assume you are using Entity Framework and you have a class setup for the entity and this is what has your [required] field.你对这里的上下文有点了解,但我假设你正在使用实体框架并且你有一个class实体设置,这就是你的[required]字段。 I am then assuming you are using this same class with your form.然后我假设您在表单中使用相同的 class。

If this is the case then, I would advise you to create a second class which will act as your view model. This way you have a data model (entity class) and a view model (front end specific class).如果是这种情况,我建议您创建第二个class ,它将充当您的视图 model。这样您就有了数据 model(实体类)和视图 model(前端特定类)。 Then you can easily separate the logic of the two behaviours.然后,您可以轻松地将两种行为的逻辑分开。

You can use something like AutoMapper to make transferring of property values between the two a little easier too.您也可以使用 AutoMapper 之类的工具来更轻松地在两者之间传输属性值。

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

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