无法在对象'dbo.User'中插入重复键。\ r \ n语句已终止

时间:2011-08-16 17:59:07

标签: entity-framework-4

我有一个用户表。对于CreatedBy等字段,可以从其他表中引用此表。

问题是,当我插入另一个表的行(比如'x')时,它会尝试将新用户插入到用户表中。

它应该做的是在CreateBy作为现有用户的表'x'中插入一行。

使用实体框架4.任何人都遇到过这样的问题吗?

1 个答案:

答案 0 :(得分:38)

您可以将实体与相关实体一起插入,也可以插入没有相关实体的实体,只需引用现有实体即可。这取决于你编写的代码。

示例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
}