Remove () не работает с отношением «многие ко многим» (ASP.NET, лямбда-выражения) - PullRequest
3 голосов
/ 18 ноября 2011

Я работаю с C # и ASP.net (4.0). Я пытаюсь удалить запись в моей таблице InterestsProfiles, используя лямбда-выражения. Таблица имеет только два столбца: идентификатор профиля и идентификатор интереса, и это внешние ключи к таблице профилей (id) и таблице интересов (id).

Итак, мне удалось добавить в таблицу профилей интересов следующий код (аргументы функции: string 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 Ответ

1 голос
/ 23 ноября 2011

Вам нужно .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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...