C# Data Annotations in Interface

允我心安 提交于 2019-12-01 03:47:28
Dan Teesdale

Placing the Data Annotation in the interface won't work. In the following link there is an explanation as to why: http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/1748587a-f13c-4dd7-9fec-c8d57014632c/

A simple explanation can be found by modifying your code as follows:

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

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

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

Then it is not clear as to whether the Bar string is required or not, since it is valid to implement more than one interface.

The Data Annotation won't work but I don't know why.

If you are using EF code first you can use Fluent API to force this behavior when creating your database. This is a workaround, not a real solution because only your database will check the constraint, not EF or any other system working with Data Annotation (well I suppose).

I did it with

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

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

Telling the system that when it recognize a class implementing IFoo you configure the property to IsRequired.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!