C# 接口中的数据注释

问题描述 投票:0回答:2

快速提问...

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

说【必填】

我可以在属性的 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;}
}
c# data-annotations
2个回答
12
投票

在界面中放置数据注释将不起作用。在以下链接中有关于原因的解释: 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字符串,因为实现多个接口是有效的


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。

© www.soinside.com 2019 - 2024. All rights reserved.