我有个小问题。
如果我在接口中添加一个符号...
说必填
我可以在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;}
}发布于 2013-06-09 12:49:49
将Data Annotation放在接口中将不起作用。在下面的链接中有一个关于原因的解释: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字符串,因为它可以有效地实现多个接口。
发布于 2016-11-25 12:35:22
数据注释不起作用,但我不知道为什么。
如果您首先使用EF代码,则可以在创建数据库时使用Fluent API强制执行此行为。这是一种变通方法,而不是真正的解决方案,因为只有您的数据库会检查约束,而不是EF或任何其他使用Data Annotation的系统(我想是这样)。
我这样做了
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。
https://stackoverflow.com/questions/17006496
复制相似问题