Dev
Dev

Reputation: 137

How do i insert data already present in one table into another using Entity framework

Hi I have table called Users which already has id of users who are registered.This table is in different database which is named TrackUsers. Now I am using new database called Terms which has field called ID which should take all ID's from users table and insert into this table.For this i used database first approach. I am using ASP.NET MVC Entity framework. Below is the code I am using in controller :

 public class HomeController : Controller
{

    private AppMarketplaceEntities db = new AppMarketplaceEntities();
    private InstallTrackerEntities db1 = new InstallTrackerEntities();


   public ActionResult Index()
    {
   List<int> gatewayUserId = new List<int>();

        using (var ctx = new InstallTrackerEntities())
        {
            gatewayUserId = ctx.Gateway_Users.Select(f => f.GatewayuserUID).ToList();
        }
        using (var ctx2 = new AppMarketplaceEntities())
        {
            foreach (var id in gatewayUserId)
            {
                ctx2.AppTerms.Add(new AppTerm() { GatewayuserUID = id });
            }
            db.SaveChanges();
        }

        return View();  
        }

        }
        }

But still GatewayUserUID is showing null in Appterms table.

Upvotes: 1

Views: 2868

Answers (1)

valentin
valentin

Reputation: 667

Assuming you have 2 .edmx files (and therefore different dbcontexts for each database), are you looking for something like this?

List<int> userids = new List<int>();
using(var ctx = new TrackUsersEntities())
{
    userids = ctx.Users.Select(f => f.UserId).ToList();
}

using(var ctx2 = new OtherDatabaseEntities())
{
    foreach(var id in userids)
    {
        ctx2.Terms.Add(new Term() { ID = id });
    }
    ctx2.SaveChanges();
}

As for where to place the code, I'd put it in the Services layer (if it exists), otherwise in the Controller class.

Upvotes: 3

Related Questions