开发者

EntityCollections setting an EntityReference.EntityKey to populate the Collection

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] [in开发者_StackOverflow社区t] 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜