接口中的C#数据注释
快速问题……
如果我在界面中加一个符号……
说[必填]
我可以在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;} }
在界面中放置数据注释将不起作用。 在以下链接中有一个解释为什么: 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字符串是否是必需的,因为它实现多个接口是有效的。
数据注释不起作用,但我不知道为什么。
如果您首先使用EF代码,则可以在创建数据库时使用Fluent API强制执行此操作。 这是一种解决方法,而不是真正的解决方案,因为只有您的数据库才会检查约束,而不是EF或任何其他使用Data Annotation的系统(我想是这样)。
我做到了
public partial class MyDbContext : DbContext { // ... code ... protected override void OnModelCreating(DbModelBuilder dbModelBuilder) { dbModelBuilder.Types().Configure(y => y.Property(e => e.Bar).IsRequired()); } }
告诉系统当它识别实现IFoo的类时,将属性配置为IsRequired。