views:

376

answers:

2

Having Trouble with Entity Framework. I have been populating EntityReferences with an EntityKey inorder to eliminate the need for querying the database ever time I add an Entity Reference. Now I want to do the same thing for an Association (EntityCollection) but im not sure where to start. below are the details of what I am trying to do

Tables

CREATE TABLE [dbo].[Foo](
 [FooId] [int] IDENTITY(1,1) NOT NULL,
 [FooName] [nvarchar](50) NOT NULL,
)
CREATE TABLE [dbo].[Bar](
 [BarId] [int] IDENTITY(1,1) NOT NULL,
 [BarName] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Bar] PRIMARY KEY CLUSTERED 
)
CREATE TABLE [dbo].[FooBar](
 [FooId] [int] NOT NULL,
 [BarId] [int] NOT NULL,
 CONSTRAINT [PK_FooBar] PRIMARY KEY CLUSTERED 
)
ALTER TABLE [dbo].[FooBar]  WITH CHECK ADD  CONSTRAINT [FK_FooBar_Bar] FOREIGN KEY([BarId])
REFERENCES [dbo].[Bar] ([BarId])

ALTER TABLE [dbo].[FooBar] CHECK CONSTRAINT [FK_FooBar_Bar]

ALTER TABLE [dbo].[FooBar]  WITH CHECK ADD  CONSTRAINT [FK_FooBar_Foo] FOREIGN KEY([FooId])
REFERENCES [dbo].[Foo] ([FooId])

ALTER TABLE [dbo].[FooBar] CHECK CONSTRAINT [FK_FooBar_Foo]

Now when I map this to the entityFramework I get 2 entities (Foo and Bar) with a Many to Many Relationship.

What Im trying to do is add a new Foo entity with 5 Bars associated I have the IDs of the Bars but I do not want to query the database to get all 5 bars. I would prefer to just set an entityKey.

Is this possible?

for example:

Foo myFoo = new Foo();
Foo.Name = "Hello"
Foo.Bars = // now I would like to just populate a set of EntityKeys for the EntityCollection
A: 

I don't think you can just set an EntityKey in this case, because the FooBar join is (or should be) an entity unto itself. You must create a new FooBar for each many-to-many relationship you want to create between Foos and Bars.

Dave Swersky
+1  A: 

Just attach a stub entity:

var bar = new Bar { Id = barId };
Context.AttachTo("Bars", bar);
myFoo.Bars.Add(bar);
Context.SaveChanges();

No DB query there for bar.

Important: You must attach bar before adding the relationship to myFoo, so that the EF knows you're not trying to insert a new Bar.

Craig Stuntz
Craig, Using stub entities seems to be a better way than populating the EntityKey and far better than querying the database again. Is this true?
John Hartsock
Depends. In EF 4 I'd probably use FK associations instead. In EF 1 stub entities are perhaps better than setting the `EntityKey`, but require (possibly indirect) access to the context.
Craig Stuntz