Remove()不适用于多对多关系(ASP.NET,lambda表达式)

时间:2011-11-18 01:57:45

标签: c# asp.net lambda

我正在使用C#和ASP.net(4.0)。我试图使用lambda表达式删除我的InterestsProfiles表中的记录。该表只有两列:profile id和interest id,这些是Profiles表(id)和Interests表(id)的外键。

所以我设法使用以下代码添加到Interests配置文件表中(该函数的参数是字符串profileID,字符串名称(感兴趣的)):

var interest = 
    context.a1Interests.Where(i => i.Interest.ToLower() == name.ToLower()).First();
if (interest == null)
  throw new HttpResponseException(HttpStatusCode.NotFound);

// Grab the profile
a1Profile profile = context.a1Profiles.Find(_id);
// Create a new profile that will be modified
a1Profile newProfile = profile;
if (profile == null)
  throw new HttpResponseException(HttpStatusCode.NotFound);

// Associate the interest with this profile
newProfile.a1Interests.Add(interest);

// Replace the old profile with the new one and save the changes
context.Entry(profile).CurrentValues.SetValues(newProfile);
context.SaveChanges();

我认为我可以使用.Remove()执行相反的删除操作,但它不起作用。该函数返回正确的对象,状态为200 / OK,但InterestsProfiles本身的条目不会被删除。

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

请帮忙。我认为这真的很简单。

1 个答案:

答案 0 :(得分:1)

编辑时需要.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