检查数据库上的现有记录我称之为web api

时间:2017-09-02 09:03:54

标签: c# asp.net-web-api entity

我正在调用web api并通过控制器保存数据库中的记录,我希望每次调用api来检查数据库中是否存在记录,如果是,则不保存,如果没有则保存。

 var client = new WebClient();
        var text = client.DownloadString("https://www.test.com/api/all-users?name=testusername%20&pass=334432");
        var wclients = JsonConvert.DeserializeObject<dynamic>(text);
        List<apicli> list1 = new List<apicli>();
        var clie = new apicli();


        if (wclients.message == "success")
        {
            var data = wclients.data;
            //var account = wclients.account;
            ViewBag.test = data;

            foreach(var item in ViewBag.test)
            {

                clie.Email = item.email;
                clie.Name = item.name;
                clie.Aff = item.affiliated_id;

                foreach(var item1 in @item.account.real)
                {
                    clie.Login = item1.login;
                    clie.password = item1.pass;

                }
                list1.Add(clie);
                db.apiclis.AddRange(list1);
                db.SaveChanges();
            };
        }

1 个答案:

答案 0 :(得分:2)

我认为你需要这样的东西,虽然你需要检查每条记录的唯一ID:

 foreach(var item in data){
            var c = new apicli  {
                Email = item.email,
                Name = item.name,
                Aff = item.affiliated_id
                Login = item.account.real.LastOrDefault()?login??"",
                Login = item.account.real.LastOrDefault()?pass??""
            }
            if(!db.apiclis.Any(a => a.Email == c.Email && a.Name == c.Name && a.Aff == c.Aff)){
                db.apiclis.Add(c);
            }
        }

这里我假设电子邮件+名称+ aff =唯一标识符。