Nil*_*Das 16 entity-framework-4
我有一个用户表.对于CreatedBy等字段,可以从其他表中引用此表.
问题是,当我插入另一个表的行(比如'x')时,它会尝试将新用户插入到用户表中.
它应该做的是在CreateBy作为现有用户的表'x'中插入一行.
使用实体框架4.任何人都面临过这样的问题吗?
Sla*_*uma 39
您可以将实体与相关实体一起插入,也可以插入没有相关实体的实体,只需引用现有实体即可.这取决于你写的代码.
例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
}
Run Code Online (Sandbox Code Playgroud)
例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
}
Run Code Online (Sandbox Code Playgroud)
例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
}
Run Code Online (Sandbox Code Playgroud)
编辑
例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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15042 次 |
| 最近记录: |