EntityCollections setting an EntityReference.EntityKey to populate the Collection

匿名 (未验证) 提交于 2019-12-03 09:13:36

问题:

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 

回答1:

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.



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!