C# Remove()不适用于多对多关系(ASP.NET、lambda表达式)
我正在使用C#和ASP.net(4.0)。我正在尝试使用lambda表达式删除我的InterestsProfiles表中的记录。该表只有两列:profile id和interest id,它们是Profiles表(id)和interest表(id)的外键 因此,我设法用以下代码添加到兴趣配置文件表中(函数的参数是stringprofileid,stringname(感兴趣的)): 我想我可以使用.Remove()来做相反的删除操作,但它不起作用。函数返回正确的对象,状态为200/OK,但不会删除InterestsProfiles中的条目C# Remove()不适用于多对多关系(ASP.NET、lambda表达式),c#,asp.net,lambda,C#,Asp.net,Lambda,我正在使用C#和ASP.net(4.0)。我正在尝试使用lambda表达式删除我的InterestsProfiles表中的记录。该表只有两列:profile id和interest id,它们是Profiles表(id)和interest表(id)的外键 因此,我设法用以下代码添加到兴趣配置文件表中(函数的参数是stringprofileid,stringname(感兴趣的)): 我想我可以使用.Remove()来做相反的删除操作,但它不起作用。函数返回正确的对象,状态为200/OK,但不会删除
newProfile.a1Interests.Remove(interest);
// Replace the old profile with the new one and save the changes
context.Entry(profile).CurrentValues.SetValues(newProfile);
context.SaveChanges();
表的创建脚本如下所示:
CREATE TABLE a1InterestsProfiles(
[Profile] [int] NOT NULL,
[Interest] [int] NOT NULL,
CONSTRAINT [PK_a1InterestsProfiles] PRIMARY KEY CLUSTERED
([Profile] ASC, [Interest] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]) ON [PRIMARY]
GO
-- Foreign key - Profiles
ALTER TABLE a1InterestsProfiles
ADD CONSTRAINT [FK_a1InterestsProfiles_Profiles]
FOREIGN KEY ([Profile]) REFERENCES a1Profiles([ID])
GO
ALTER TABLE a1InterestsProfiles CHECK CONSTRAINT [FK_a1InterestsProfiles_Profiles]
GO
-- Foreign key - Interests
ALTER TABLE a1InterestsProfiles
ADD CONSTRAINT [FK_a1InterestsProfiles_Interests]
FOREIGN KEY ([Interest]) REFERENCES a1Interests ([ID])
GO
ALTER TABLE a1InterestsProfiles CHECK CONSTRAINT [FK_a1InterestsProfiles_Interests]
GO
请帮忙。我认为这将非常简单。在编辑它时,您需要.Attach()
和实体
加
a1Profile profile = context.a1Profiles.Find(_id);
a1Profile.a1Interests.Add(interest);
context.SaveChanges();
除去
newProfile.a1Interests.Remove(interest);
context.a1Profiles.Attach(newProfile);
context.SaveChanges();
还值得一看
EntityState.Modified
您使用的是什么数据访问技术?LINQ to SQL、LINQ to Entities或其他什么?sq33G:它返回它应该返回的对象和200/OK状态,但InterestsProfiles中的条目没有被删除。Kirk Broadhurst:恐怕我不知道术语。如果有帮助,我创建了一个ADO.NET实体数据模型,并且从edmx文件中,这些类是用ADO.NET DbContext Generator创建的。@daoberes如果您用@标记其他海报的名称,您的评论将显示在他们的SO收件箱中。
newProfile.a1Interests.Remove(interest);
context.a1Profiles.Attach(newProfile);
context.SaveChanges();