none
database first does not retrieve string length from database RRS feed

  • General discussion

  • i use ef6 and vs2013 and i want to create the model from an existing database.

    The model is created but the length of the sql field is not set to the model

    How can i retrieve the stringlength from the database when i create a model from database?

            [StringLength(4)]
            public string ActualValue { get; set; }


    • Edited by iglezos Saturday, May 10, 2014 8:25 PM
    Saturday, May 10, 2014 8:24 PM

All replies

  • I guess you are looking to do some kind of length validation on a string. There several ways to do it.

    http://msdn.microsoft.com/en-us/data/gg193959.aspx

    I can tell you that EF 6 will throw a truncation exception message if string data is greater than max length of the column in the database table definition when the object is persisted to the database. 

    Saturday, May 10, 2014 10:19 PM
  • what i actually need is to retrieve the lenght inofrmation from database when i create the model.

    lets say i have a database with  a table customers and a field Description nvarchar(80) not null. When i create the model with database first to automatically create a model like

    public class Customers{
         [Required]
         [StringLength(80)]
         public string Description { get; set; }
    }

    Sunday, May 11, 2014 4:27 AM
  • The only way you can do it would be to read the EDMX file, which is XML. It has all the objects on the model, and the properties of the object have attributes such as MaxLength value. You can read the EDMX with something like Linq-2-XML after the fact that the EDMX file, the model, has been created. That's the only way that I know of that you can access that type of information.

    But on the other hand, you can just printout a database table schema and do it manually. That is type the number for the length from the printout of the table schema.

    I don't think anything is going to be viable as to what you are wanting to do.

    Sunday, May 11, 2014 5:13 AM
  • i found a solution to the following link

    http://msdn.microsoft.com/en-us/data/jj593170.aspx

    Sunday, May 11, 2014 8:07 AM
  • What solution, because I don't see it.
    Sunday, May 11, 2014 10:05 AM
  • by using EF tools, i created the model from the existing database by "reverse engineering" option. There were automatically created files in the model with code like the following

    public CustomerMap()
            {
                // Primary Key
                this.HasKey(t => t.ID);
    
                // Properties
                this.Property(t => t.Code)
                    .IsRequired()
                    .HasMaxLength(25);
    that gives the validation i required

    Tuesday, May 13, 2014 5:26 AM