复制数据库中的行,使用LINQ

时间:2018-04-10 21:05:12

标签: asp.net linq

我想在我的租户表中创建一条新记录,只更改tenantEmail和tenantPhone。该表有很多列,所以我想做类似的事情:

var getTenant = db.tenants.Where(x => x.TenantID == 1).FirstOrDefault();
tenant t = new tenant();
t = getTenant;
t.TenantEmail = "NEWEMAIL";
t.TenantPhone = "NEWPHONE";
// How can I insert this new tenant? Will it have the some TenantID (I don't want the same tenant id)?

由于

2 个答案:

答案 0 :(得分:1)

使用.AsNoTracking()它将删除与数据库的关联,然后您可以更改所需的几个字段并保留所有其他字段,并将其添加为新对象。在添加之前,只需将ID字段设置为null。

var getTenant = db.tenants
    .Where(x => x.TenantID == 1)
    .AsNoTracking()
    .FirstOrDefault();

... change your fields

   db.tenants.Add(getTenant)

答案 1 :(得分:1)

我认为db是您的dbContext

//If `TenantId` is your primary key
var tenant = dbContext.tenants.Find(_tenantId); 

//If not then use `where` to get the record from the database
var tenant = dbContext.tenants.FirstOrDefault(x=>x.TenantId==_tenantId);  

//Detach it from the context
dbContext.Entry(tenant).State = EntityState.Detached;

//add the new values and don't forget to set the primary key value to 0
tenant.TenantId=0;

tenant.TenantEmail = "NEWEMAIL";
tenant.TenantPhone = "NEWPHONE";

//Add it to the context
dbContext.Entry(tenant).State = EntityState.Added; 
//Or add it to tenants list
dbContext.tenants.Add(tenant);

//Create a new record by calling save changes
dbContext.SaveChanges();