相关疑难解决方法(0)

如何定位记录类的属性?

定义记录类时,如何将属性定位到参数、字段或属性?

例如,我想使用,JsonIgnore但这不能编译,因为它对字段或属性有属性使用限制:

record Person(string FirstName, string LastName, [JsonIgnore] int Age);
Run Code Online (Sandbox Code Playgroud)

c# oop attributes c#-9.0 record-classes

15
推荐指数
2
解决办法
759
查看次数

记录中的数据注释在单元测试中失败

目前我们正在建立一个新项目,并希望使用 C# 9 中引入的新记录。我们遇到了在单元测试期间未触发记录(构造函数)内的 DataAnnotations 的问题。

现在,在调用控制器时会触发 DataAnnotation,但是当我尝试在单元测试中模拟它时(请参阅下面的代码),它永远不会返回任何错误。

        //Unit Testing ASP.NET DataAnnotations validation
        //http://stackoverflow.com/questions/2167811/unit-testing-asp-net-dataannotations-validation
        protected static IList<ValidationResult> ValidateModel(object model)
        {
            var validationResults = new List<ValidationResult>();
            var ctx = new ValidationContext(model, null, null);
            Validator.TryValidateObject(model, ctx, validationResults, true);
            return validationResults;
        }
Run Code Online (Sandbox Code Playgroud)

目前我们创建了一个解决方法:

    public record FooRecord(string BarProperty)
    {
        [Required]
        public string BarProperty { get; init; } = BarProperty;

    }
Run Code Online (Sandbox Code Playgroud)

但我希望有人知道为什么会发生这种情况,并且也许知道如何使用简写语法来解决这个问题:

    public record FooRecord([Required] BarProperty){ }
Run Code Online (Sandbox Code Playgroud)

c# record xunit .net-5 c#-9.0

4
推荐指数
1
解决办法
2291
查看次数

ASP.NET Core 中的位置记录属性

感谢审稿人找到重复内容:How do I target attribute for a record class?

.NET 5.0 Web API不适用于具有所需属性的记录也与之相关。

我试图理解为什么 3. 位置记录属性在下面不起作用。

这是一个新的 ASP.NET Core Razor Pages Web 应用程序,其源代码位于https://github.com/djhmateer/record-test

https://daveabrock.com/2020/11/18/simplify-api-models-with-records似乎已经让它与 API 一起使用。

public class LoginModelNRTB : PageModel
{
    [BindProperty]
    // there will never be an InputModel on get
    // but if we set to nullable InputModel then the cshtml will produce dereference warnings
    // https://stackoverflow.com/a/54973095/26086
    // so this will get rid of the warnings as we are happy we will never …
Run Code Online (Sandbox Code Playgroud)

c# record asp.net-core nullable-reference-types

1
推荐指数
1
解决办法
1371
查看次数