This post has reference to part one of this Article.
Create a new Class with the name "MyLinq". We are going to use the DataContextFactory Class which we created in Part One. Also assume in our database we have Table with name "User" and with the following Definition.
Also inside the "Linq to Sql" Template, the name of the "User" Table interface is "UserEntity". Now lets see how we can INSERT or UPDATE Data Rows in the User Table. Use the following block of code within MyLinq class,
public void InsertOrUpdateUserProfile(string userName, string phoneNumber)
{
using (DataDataContext db = DataContextFactory.CreateContext())
using (DataDataContext db = DataContextFactory.CreateContext())
{
InsertUpdateUser(db, userName, phoneNumber);
db.SubmitChanges();
}
}
InsertUpdateUser(db, userName, phoneNumber);
db.SubmitChanges();
}
}
private void InsertUpdateUser(DataDataContext db, string userName, string phonenumber)
{
try
{
var userentity = (from entity in db.UserEntities
where entity.UserName == userName
select entity)
List<UserEntity> uE = userentity.ToList();
if (uE.Count == 0)
{
UserEntity userE = new UserEntity();
userE.UserName = userName;
userE.PhoneNumber = phonenumber;
db.UserEntities.InsertOnSubmit(userE);
}
else
{
{
try
{
var userentity = (from entity in db.UserEntities
where entity.UserName == userName
select entity)
List<UserEntity> uE = userentity.ToList();
if (uE.Count == 0)
{
UserEntity userE = new UserEntity();
userE.UserName = userName;
userE.PhoneNumber = phonenumber;
db.UserEntities.InsertOnSubmit(userE);
}
else
{
// Not more than one element is considered
UserEntity userE = userentity.Single();
userE.PhoneNumber = phonenumber;
}
}
catch(Exception)
{
throw new Exception("Unable to Insert or Update the Database");
}
}
userE.PhoneNumber = phonenumber;
}
}
catch(Exception)
{
throw new Exception("Unable to Insert or Update the Database");
}
}
Now use the below Two methods to DELETE option,
public void DeleteUserProfile(string userName)
{
using (DataDataContext db = DataContextFactory.CreateContext())
{
DeleteUser(db, userName);
db.SubmitChanges();
}
}
{
using (DataDataContext db = DataContextFactory.CreateContext())
{
DeleteUser(db, userName);
db.SubmitChanges();
}
}
private void DeleteUser(DataDataContext db, string userName)
{
try
{
db.UserEntities.DeleteAllOnSubmit(from entity in db.UserEntities
where entity.UserName == userName
select entity);
}
catch (Exception)
{
throw new Exception("Unable to Delete");
}
}
{
try
{
db.UserEntities.DeleteAllOnSubmit(from entity in db.UserEntities
where entity.UserName == userName
select entity);
}
catch (Exception)
{
throw new Exception("Unable to Delete");
}
}
0 comments:
Post a Comment