views:

114

answers:

2

Suppose I have two table tab1, tab2. EF will create a edmx file and there are two entities created.

Then I want to add a computer member to tab1, which get some result from tab2, such as count, sum. What I used is partial class:

public partial class tab1{
   public int Count{
      get{
             int cnt;
             //...
             return cnt;
         }
   }
   public int Total{
      get{
             int total;
             //the matching sql like select sum(column) from tab2
             return total;
         }
   }
}

I want to cnt is counts in tab2(so the SQL should be select count(1) from tab2). Or total which is calculated from another table. But how to implement it? there is no something like datacontext yet.

A: 

If you're writing these sorts of properties yourself, it sounds like you haven't rigged up the entity framework navigation properties and association mappings.

Try add a foreign key to your database between the tab1 and tab2 tables (however they are related) and then wipe your edmx file and import the entire thing again. You should see that there is now an association between tab1 and tab2 in the entity framework designer.

You could then call something like:

myTab1.Tab2s.Count();

Hopefully that helps - Loren Van Spronsen

LorenVS
Thank you. But I am looking for compute member in general. I took the count as example. Another example maybe Sum of some some column from other table, which maybe has no proper association with the tab1 than can be identity by foreign key ect.
KentZhou
Is there a relationship between tab1 and tab2?If not, why are you trying to put these properties into tab1?If so, then you should be able to calculate these values in tab1. For the Sum example, you could use (from t in this.Tab2s select t.Value).Sum()
LorenVS
+2  A: 

Yes there is - use the ObjectContext ! That's your "entry point into all things for Entity Framework.

You named it when you created the EDMX - it's the same name that's used for your Entity Framework connection string. It's a class in your "mymodel.designer.cs" code-behind file for the EDMX model.

using(MyModelContext ctx = new MyModelContext())
{
   tab1 newTab = new tab1();
   // set the properties as you wish

   ctx.AddTotab1(newTab);
   ctx.SaveChanges();
}

If your "tab1" and "tab2" entities are linked in a 1:n fashion (one "tab1" can have multiple "tab2" entries), you'll find a member of "tab1" of type "EntityCollection" - let's say this is called "tab2Entities".

Now if you want to calculate the number of "tab2" entries for a given "tab1" object, just use this code:

if(!tab2Entities.IsLoaded())
   tab2Entities.Load();

int count = tab2Entities.Count;

That's all there is! :-)

Marc

marc_s