Невозможно вставить повторяющийся ключ в объект 'dbo.User'. \ R \ nОтношение завершено - PullRequest
15 голосов
/ 16 августа 2011

У меня есть таблица пользователей. есть ссылки на эту таблицу из других таблиц для таких полей, как CreatedBy.

Проблема в том, что когда я вставляю строку другой таблицы (скажем, 'x'), он пытается вставить нового пользователя в пользовательскую таблицу.

Что нужно сделать, это вставить строку в таблицу 'x' с CreatedBy в качестве существующего пользователя.

Использование Entity Framework 4. Кто-нибудь сталкивался с подобной проблемой раньше?

1 Ответ

38 голосов
/ 16 августа 2011

Вы можете вставить объект вместе со связанными объектами или вы можете вставить объект без связанных объектов, просто ссылаясь на существующие.Это зависит от кода, который вы пишете.

Пример 1:

User user = GetUserFromSomewhere();
using (var context = new MyContext())
{
    Order order = new Order();
    order.CreatedBy = user;

    context.Orders.AddObject(order);
    // will put both order and related entity user into Added state
    // because user is not attached to the context

    context.SaveChanges();
    // creates new order and new user and sets the relationship between them
}

Пример 2:

using (var context = new MyContext())
{
    User user = context.Users.SingleOrDefault(u => u.Id == 1);
    // query attaches this user to this context
    // user is in state Unchanged now

    Order order = new Order();
    order.CreatedBy = user;

    context.Orders.AddObject(order);
    // will put the order into Added state but doesn't touch the
    // state of already attached related entities -> user remains
    // in state Unchanged

    context.SaveChanges();
    // creates new order with reference to user, but doesn't create new user
}

Пример 3:

User user = GetUserFromSomewhere();
using (var context = new MyContext())
{
    context.Users.Attach(user);
    // we attach explicitely to the context telling EF thereby
    // that we know that this user exists in the DB
    // user is in state Unchanged now

    Order order = new Order();
    order.CreatedBy = user;

    context.Orders.AddObject(order);
    // will put the order into Added state but doesn't touch the
    // state of already attached related entities -> user remains
    // in state Unchanged

    context.SaveChanges();
    // creates new order with reference to user, but doesn't create new user
}

Редактировать

Пример 4:

int userId = GetUserIdFromSomewhere();
using (var context = new MyContext())
{
    var user = new User { Id = userId };
    // we create a stub user entity with the correct primary key
    // It's not necessary to set other properties
    // to only set the relationship to the order

    context.Users.Attach(user);
    // we attach explicitely to the context telling EF thereby
    // that we know that this user exists in the DB
    // user is in state Unchanged now

    Order order = new Order();
    order.CreatedBy = user;

    context.Orders.AddObject(order);
    // will put the order into Added state but doesn't touch the
    // state of already attached related entities -> user remains
    // in state Unchanged

    context.SaveChanges();
    // creates new order with reference to user, but doesn't create new user
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...