9

快速提问...

如果我在界面中添加符号...

说[必填]

我可以在属性的 C# 类中省略该符号吗?

即我可以...

Interface IFoo
{
   [Required]
   string Bar {get; set;}
}

Class Foo : IFoo
{
   string Bar {get; set;}
}

还是我不需要将符号放在界面中并执行此操作...

Interface IFoo
{
   string Bar {get; set;}
}

Class Foo : IFoo
{
   [Required]
   string Bar {get; set;}
}
4

2 回答 2

10

将数据注释放在界面中将不起作用。在下面的链接中有一个解释为什么: http ://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/1748587a-f13c-4dd7-9fec-c8d57014632c/

通过如下修改代码可以找到一个简单的解释:

interface IFoo
{
   [Required]
   string Bar { get; set; }
}

interface IBar
{
   string Bar { get; set; }
}

class Foo : IFoo, IBar
{
   public string Bar { get; set; }
}

然后不清楚是否需要 Bar 字符串,因为实现多个接口是有效的。

于 2013-06-09T04:49:49.493 回答
0

数据注释不起作用,但我不知道为什么。

如果您首先使用 EF 代码,则可以在创建数据库时使用 Fluent API 强制执行此行为。这是一种解决方法,而不是真正的解决方案,因为只有您的数据库会检查约束,而不是 EF 或任何其他使用数据注释的系统(我想)。

我做到了

public partial class MyDbContext : DbContext
{
    // ... code ...

    protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
    {
        dbModelBuilder.Types<IFoo>().Configure(y => y.Property(e => e.Bar).IsRequired());
    }
}

告诉系统,当它识别出实现 IFoo 的类时,您将属性配置为 IsRequired。

于 2016-11-25T04:35:21.887 回答