How can I set default values in Entity Framework

十年热恋 提交于 2019-12-23 19:13:18

问题


I've a table with 52 columns in my database and I want to write a function to create a row in that table.
In my case, I don't want to use all columns in that table, so I created my model like this.

[Table("CUST_MASTER")]
public class CustomerMaster
{
    [Key]
    [Column("CUSTOMER_ID")]
    public string Id { get; set; }

    [Column("CUSTOMER_NAME")]
    public string Name { get; set; }

    [Column("CUSTOMER_CITY")]
    public string City { get; set; }
 }

Is there any way to send only this data via Entity framework and set all other not nullable fields to some default data(for strings "", for decimals 0.0, etc.) without writing all that fields in my model and doing it manually?


回答1:


When you do not incorporate a Table-column in your model then it won't be mapped and it will be totally ignored by all generated SQL.

So the only option is to specify a default value in your Database.




回答2:


If you set the values in the constructor you will have a default value through your code, but you could look into enabling migrations instead, this way you can set default values. look at this stackoverflow question




回答3:


I think this old suggestion is what you want. It explicitly mentions the lack of mapping between the conceptual model and the storage model. Not a very popular/understood idea though.

Update: FWIW, this suggests that it is already possible in non-Code-First scenarios.



来源:https://stackoverflow.com/questions/10427358/how-can-i-set-default-values-in-entity-framework

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