简体   繁体   中英

How to selected and item from Entity and insert the item in other table having same structure using c#?

I am fetching an item from one table and inserting into other table having same table structure how to do using LINQ to entity in C# ?

public static void GetInfillIDAndInsertIntoInfillPO(int infillID)
{
    Entities db = new Entities();
    List<Infill> infillitem = (from c in db.Infills
                                    where (c.InfillID == infillID)
                                    select c).ToList();

    List<InfillPO> infillPO = new List<InfillPO>();

    db.InfillPOes.Add(infillitem);

}

Here Infill and InfillPO have same table structure. Just the InfillPO doesn't contain the Primary key . Now, i just want to insert the record as it is in InfillPO table.

I have also tried it by casting. but wont work.

public static void GetInfillIDAndInsertIntoInfillPO(int infillID)
{
    XtremeProcurementEntities db = new XtremeProcurementEntities();
    Infill infillitem = (from c in db.Infills
                                where (c.InfillID == infillID)
                                select c).FirstOrDefault();

    InfillPO infillPO = new InfillPO();

    db.InfillPOes.Add((infillPO)infillitem);                
}

Help appreciated!

You make a select of Type T1 from the Table and select it into T2. This T2 you can then add to the context and save it.

List<InfillPO> infillitem = (from c in db.Infills
                                       where (c.InfillID == infillID)
                                               select new InfillPO
                             {
                                  PropertyA = c.PropertyA
                             }).ToList();

This would be the easiest and fastest solution. Depends if you want to change the Columns frequently...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM