简体   繁体   中英

ado.net entity data model finding a row? then calling an if statment

I am having trouble with finding out if a record from my SQL table has anything in it and I am not sure where i am going wrong. This is how far I am currently:

 using (var context = new SADWorkshopEntities())
        {
            var query = (from p in context.user_profile
                         where p.deviceID == deviceid
                         select p);
            if (query == null)
            {
                context.user_profile.Add(new user_profile()
                {
                    deviceID = deviceid,
                    uri = subscriberUri
                });
                context.SaveChanges();
            }

The code for adding the device id and uri works but it isn't called since I added the if statement I put it in. I am trying to say if there is no records with the same deviceid then create a new record then I am going to try to add an update record query for if there is a record but I am struggling.

Thanks

Try

using (var context = new SADWorkshopEntities())
        {
            var query = (from p in context.user_profile
                         where p.deviceID == deviceid
                         select p).FirstOrDefault();
            if (query == null)
            {
                context.user_profile.Add(new user_profile()
                {
                    deviceID = deviceid,
                    uri = subscriberUri
                });
                context.SaveChanges();
            }

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