Entity Framework Code First Computed Properties

人走茶凉 提交于 2019-11-30 08:13:37

I've found the solution. Entity Framework provides a data annotation called DatabaseGenerated. Use it like this:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string ChargePointText { get; set; }

Get more details here: http://msdn.microsoft.com/en-us/library/gg193958.aspx

There are a couple of other options as well.

The first is to change the property setup in the mapping file from:

this.Property(t => t.Name)
    .HasMaxLength(152);

to:

this.Property(t => t.Name)
    .HasMaxLength(152)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

This is pretty much the same as Same Huggill's solution, except it keeps this configuration in the mapping, rather than in the model. I feel this is slightly better since the mapping class already contains code to tell Entity Framework how to load that type of entity, so the knowledge that a field is computed belongs in there.

Another option is the NotMappedAttribute which can be applied to individual properties of an entity like so:

public class User
{
    ...

    [NotMapped]
    public string Name
    {
        get;
        set;
    }

    ...
}

This is useful for when the entity contains properties that are not populated from the database, but it should be equally useful in the scenario faced by OP, i.e., EF will not try to push the value in a property marked with the NotMappedAttribute, therefore insert should work.

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