如何使用 LINQ 将 C# 类对象添加到实体表中
本文关键字:添加 实体 对象 何使用 LINQ | 更新日期: 2023-09-27 18:35:08
如何使用 LINQ 将类对象添加到 Enitity 表中???处方器对象是从 FullMasters 实体构建的,但我需要获取该对象并将其保存到表中EPCS_Prescriber。我正在使用 linq。
public class UserRepository : IUserRepository
{
SourceofTruthEntities context = null;
ePrescribeEntities epcs = null;
public UserRepository()
{
context = new SourceofTruthEntities();
}
public List<FullMaster> SelectByNPI(string id)
{
var data = context.FullMasters.Where(x => x.NPI == id).ToList();
return data;
}
public List<FullMaster> SelectByName(string first, string last)
{
var data = context.FullMasters.Where(x => x.FirstName == first && x.LastName == last).ToList();
return data;
}
public void SavePrescriber(string id)
{
var data = context.FullMasters.Where(x => x.NPI == id).FirstOrDefault();
Prescriber p = new Prescriber
{
First = data.FirstName,
Last = data.LastName,
DEA = data.DEA,
License = data.LIC,
Life = data.Life_Hosp,
NPI = data.NPI
};
epcs.EPCS_Prescriber.Add(p);
epcs.SaveChanges();
}
}
public void SavePrescriber(string id)
{
var data = context.FullMasters.Where(x => x.NPI == id).FirstOrDefault();
EPCS_Prescriber e = new EPCS_Prescriber();
e.FirstName = data.FirstName;
e.LastName = data.LastName;
e.DeaNo = data.DEA;
e.License = data.LIC;
e.LifeNo = data.Life_Hosp;
e.NpiNo = data.NPI;
epcs.EPCS_Prescriber.AddObject(e);
epcs.SaveChanges();
}
您的两个上下文都需要初始化:
public UserRepository()
{
context = new SourceofTruthEntities();
ePrescribeEntities epcs = new ePrescribeEntities();
}
假设epcs
是数据库上下文,那么你应该使用epcs.EPCS_Prescriber.Insert(p)
而不是AddObject(p)
除非这不是一个数据库,否则您肯定只需要一个上下文吗?这应该适合您:
public void SavePrescriber(string id)
{
var data = context.FullMasters.Where(x => x.NPI == id).FirstOrDefault();
Prescriber p = new Prescriber
{
First = data.FirstName,
Last = data.LastName,
DEA = data.DEA,
License = data.LIC,
Life = data.Life_Hosp,
NPI = data.NPI
};
context.EPCS_Prescribers.Add(p);
context.SaveChanges();
}
确保您的...DbContext 类包含以下内容:
...
public System.Data.Entity.DbSet<YourNamespace.Models.Prescriber> EPCS_Prescribers { get; set; }
...
如有必要,请检查类/实体的名称。