Dev
Dev

Reputation: 137

How do i avoid getting duplicate results in Entity framework

Hi i am using following code to fetch userID present in Gateway_users table to Appterms table. But problem is whenever i run solution I am getting duplicate records, that is first time 100 records with ID's and second time 200 records with duplicate ID's so on.

 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 });
            }
            ctx2.SaveChanges();
        }

        return View();  
     } } }

So what changes I have to make to above code to get only ID's which are present in Gateway_users table and it should fetch only once and not duplicate records.

Upvotes: 0

Views: 1348

Answers (2)

Pedro.The.Kid
Pedro.The.Kid

Reputation: 2078

What is happening is you are always adding the InstallTrackerEntities GatewayuserUID List to the AppMarketplaceEntities AppTerms List and what you want is to only insert the new ones.

first if you want to remove the ones ho no longer exist in InstallTrackerEntities the easiest way is to just clear the AppTerms table and insert the new list as Tony Lunt says.

to just insert the ones ho are new create a list of the ones already in AppMarketplaceEntities and only insert the ones not present

    using (var ctx = new InstallTrackerEntities())
    {
        gatewayUserId = ctx.Gateway_Users.Select(f => f.GatewayuserUID).ToList();
    }
    using (var ctx2 = new AppMarketplaceEntities())
    {
        var appTermsUIDs = ctx2.AppTerms.Select(f => f.GatewayuserUID).ToList();

        foreach (var id in gatewayUserId.Where(e => !appTermsUIDs.Contains(e)))
        {
            ctx2.AppTerms.Add(new AppTerm(){ GatewayuserUID = id });
        }
        ctx2.SaveChanges();
    }

Upvotes: 2

Tony Lunt
Tony Lunt

Reputation: 1

You need to clear your second table (ctx2.AppTerms) if you're wanting to receive only new ID's every time. Otherwise, you're just appending new data on top of your old data. That would explain the "duplicates". For an example of this, see this answer: https://stackoverflow.com/a/15220460/1634770. Basically, you need to do something like this:

var objCtx2 = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)ctx2).ObjectContext;
objCtx2.ExecuteStoreCommand("TRUNCATE TABLE AppTerms");

Upvotes: 0

Related Questions