Mick Mick - 2 months ago 6
ASP.NET (C#) Question

Can i add columns my database and then add properties in my models corresponding to those columns?

I have an MVC project which uses entity framework. I need to add some columns to my database. Is it possible to just write an SQL script to add columns to the database and then add some properties in my models that match the added columns? I kind of try to avoid code-first migrations here. Would my approach work? If not, what is the best solution to this problem?

Thanks in advance

Answer

Yes, of course it is possible. If your tables are following Entity Framework naming conventions, all you have to do is add new column and add new property in proper entity class with the same name as your new column.

public class Stuff{
    public int ID { get; set; }
    public string Name { get; set; }
    //your new column in database is named "NewColumn"
    public string NewColumn { get; set; }
}

If you are not following this conventions, you should decorate your new property in entity class with Column annotation to explicitly tell Entity Framework where he should look for value for this property.

public class Stuff{
    public int ID { get; set; }
    public string Name { get; set; }
    //your new column
    [Column("my_new_column")]
    public string NewColumn { get; set; }
}