1

Is it possible to map computed columns into Code First model? I'd like to define computed columns with SQL Server and then map them as properties inside my CF model.

Thanks in advance

Best Regards

Larry
  • 573
  • 5
  • 14
  • 31

3 Answers3

3

Use the DatabaseGenerated attribute with DatabaseGeneratedOption.Computed as the value

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string Foo { get; set; }
Eranga
  • 32,181
  • 5
  • 97
  • 96
  • Thank you very much @Eranga! I found [this answer](http://stackoverflow.com/a/6995622/1129461) too, where Mr @Goran Obradovic specify to use `DELETE FROM [dbo].[EdmMetadata]` too. I still have not been able to test these procedures, you tell me if you have to delete edmmetadata too? Thank you! – Larry Feb 13 '12 at 09:20
  • I succeed to get it work using the `[DatabaseGenerated(DatabaseGeneratedOption.Computed)]' attributes, as suggested by Eranga **AND dropping the columns BEFORE** creating the new computed columns during the first Data Init (DataFeed) of the solution. THX @Eranga! – Larry Feb 13 '12 at 21:42
0

I think for EFCF beginners (like me!), there is no need for creating Database Initializers, this just work:

Model1 model = new Model1();//Model1 : DbContext
model.Database.CreateIfNotExists();
model.Database.ExecuteSqlCommand("alter table Results drop column Total; alter table Results add Total AS (Arabic + English + Math + Science)");

for the complete answer check here.

0

Not sure how you would do computed columns without using a view, and you cannot use views in EF Code First (you can in Model & DB first though). EF will execute some operations in SQL for you, instead of in code, but it doesn't sound like that is what you're looking for. Can you elaborate on what you are trying to achieve?

Community
  • 1
  • 1
RyanR
  • 7,728
  • 1
  • 25
  • 39
  • Thx @RyanR. I am trying to access computed columns with DataObject, for example. If I have all fields 'wired' into dbset, I won't have problems of 'Pure Entity' problems I described in [my question](http://stackoverflow.com/q/9027150/1129461). Following @Oleg 's suggestions, I think the best way is to put calculated properties directly inside my db. For now it seems the right direction, putting these annotations to the properties: `[NotMapped] [DatabaseGenerated(DatabaseGeneratedOption.Computed)]`... – Larry Feb 13 '12 at 11:50
  • Not true, you can use and model views in EF Code First. You just can't get them to generate themselves, you have to create them another way, without the Code First DatabaseGeneration stuff. – Scott Stafford Mar 07 '13 at 19:51
  • @ScottStafford I would like to see that work - do you have an example or any documentation you can link to? – RyanR Mar 09 '13 at 19:30