How to not specify SQL expression in HasComputedColumnSql of EF Core Fluent API in DB first approach?

ε祈祈猫儿з 提交于 2019-12-11 05:01:22

问题


In previous version of EF, to specify a computed column we would write:

modelBuilder
.Entity<Type>()
.Property(x => x.ComuptedProperty)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

This would make sense, because the SQL expression for the computed column is written once in database.

However, after migrating to EF Core, we realized that the syntax should be changed into:

modelBuilder
.Entity<Type>()
.Property(x => x.ComuptedProperty)
.HasComputedColumnSql("SQL Expression should be duplicated here");

This makes sense when we go code first. Because EF Core uses this SQL expression while creating the table.

However, for DB first scenarios this doesn't make sense at all. We tried to leave this parameter empty, and it throws an exception complaining:

The string argument 'sql' cannot be empty

Now things get even worse when you want to have a data access generator. How can we neglect this parameter?


回答1:


Indeed when using HasComputedColumnSql you must specfiy the SQL query that will be used for the computed column when generating SQL Script for the associated table. Like you say, this is useful only for Code First approach.

In Database First approach, you can use one of the following methods frol PropertyBuilder<TProperty> type (description are from XML documentaiton of those methods):

  • ValueGeneratedOnAdd(): Configures a property to have a value generated only when saving a new entity,unless a non-null, non-temporary value has been set, in which case the set value will be saved instead. The value may be generated by a client-side value generator or may be generated by the database as part of saving the entity.
  • ValueGeneratedOnAddOrUpdate(): Configures a property to have a value generated when saving a new or existing entity.
  • ValueGeneratedOnUpdate(): Configures a property to have a value generated when saving an existing entity.

In your case because it's a computed column then the value maybe generated when adding and saving the data so you must use ValueGeneratedOnAddOrUpdate() method. Again EF documentation say that :

This just lets EF know that values are generated for added or updated entities, it does not guarantee that EF will setup the actual mechanism to generate values.



来源:https://stackoverflow.com/questions/47575834/how-to-not-specify-sql-expression-in-hascomputedcolumnsql-of-ef-core-fluent-api

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