简体   繁体   中英

Calculated values on Entity Framework entities

In my project, i have an entity named Product containing a property Price I need to calculate the taxes for each product so i made a Model defined function like in this tutorial http://blogs.msdn.com/b/efdesign/archive/2009/01/07/model-defined-functions.aspx

Everything works fine, Generated SQL is clean but i have a problem.

I would need to get the taxes for an entity i've just made (an Product object not stored in database). Is it possible to use a model defined function for an object like this ? If not, how Can I make a method to calculate the taxes with the same method from linq and from pure C# code ?

Thank's by advance.

What I would do is create a user-defined function in SQL Server, use that to fill your computed column, then simply call it from your application to fill the value in your newly-created object's tax value.

Unfortunately, last time I checked, it's rather clumsy calling a UDF in EF4, so what I did, and I know this isn't the cleanest thing in the world, is add a LINQ-to-SQL data context, add the UDF to that , and then just call the UDF as though it were a C# method from there.

To make things a bit cleaner, I went one more step and added the same method definition to my EF4 ObjectContext (by hand, via a partial class) and then called the method on my EF context, which then called the method on an instance of the L2S context.

I know it seems like a lot, but it's not too bad at all in practice. Calling UDFs in EF4 is the one thing that's not quite as convenient as L2S.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM