문제

I have a big database existing database to comunicate with, and I'm using EF 5.0 database first, the problem I'm having is that if I create any data decoration like [stringlength(50)] on the class and then the databases is uploaded, when I "upload from database" all data annotations are gone. How can I do to keep them?

도움이 되었습니까?

해결책

It's very simple: You Can't! Because those codes are auto-generated and will be over written on each model update or change.

However you can achieve what you need through extending models. Suppose that EF generated the following entity class for you:

namespace YourSolution
{
    using System;
    using System.Collections.Generic;

    public partial class News
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }        
        public int UserID { get; set; }

        public virtual UserProfile User{ get; set; }
    }
}

and you want do some work arounds to preserve your you data annotations and attributes. So, follow these steps:

First, add two classes some where (wherever you want, but it's better to be in Models) like the following:

namespace YourSolution
{
    [MetadataType(typeof(NewsAttribs))]
    public partial class News
    {
         // leave it empty.
    }

    public class NewsAttribs
    {            
        // Your attribs will come here.
    }
}

then add what properties and attributes you want to the second class - NewsAttribs here. :

public class NewsAttrib
{
    [Display(Name = "News title")]
    [Required(ErrorMessage = "Please enter the news title.")]
    public string Title { get; set; }

    // and other properties you want...
}

Notes:

1) The namespace of the generated entity class and your classes must be the same - here YourSolution.

2) your first class must be partial and its name must be the same as EF generated class.

Go through this and your attribs never been lost again ...

다른 팁

The accepted answer may work for standard data operations, but I am trying to validate the model prior to the call to DbSet.Add using TryValidateObject. With the accepted answer, it is still not picking up on the data annotations.

What did work for me I found in a .NET Runtime GitHub thread, as proposed by what I'm inferring is one of the .NET developers.

Basically, this is a bug, and you have to force the model to recognize the metadata decorations using TypeDescriptor.AddProviderTransparent . . .

TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(News), typeof(NewsAttrib)), typeof(News));

Once I make this call, TryValidateObject recognizes the data annotations and returns false when any of the constraints are not met.

Here's the link. I little more than half-way down, there's a working code sample in a .zip file.

https://github.com/dotnet/runtime/issues/46678

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top