我如何使用 WCF 服务中的自我跟踪实体来实现 ServiceContract
这是我在IPbService.cs中的 ServiceContract
namespace PhoneBookService
{
[ServiceContract]
public interface IPbService
{
[OperationContract]
List<User> GetAllUser();
[OperationContract]
string AddUser(User user);
[OperationContract]
string DeleteUser(int id);
[OperationContract]
string UpdateUser(User user);
[OperationContract]
List<Contact> GetContactsByUser(int id);
[OperationContract]
string AddContact(Contact contact, string userName);
[OperationContract]
string DeleteContact(int id);
[OperationContract]
string UpdateContact(Contact contact);
}
}
这是我在PbService.svc.cs中的实现类
namespace PhoneBookService
{
public class PbService : IPbService
{
readonly PhoneBookDBEntities _context = new PhoneBookDBEntities();
public List<User> GetAllUser()
{
return _context.Users.OrderBy(u => u.Name).ToList();
}
public string AddUser(User user)
{
try
{
_context.Users.AddObject(user);
_context.SaveChanges();
return "";
}
catch (Exception e)
{
return e.Message;
}
}
public string DeleteUser(int id)
{
try
{
User user = _context.Users.FirstOrDefault(u => u.UserID == id);
_context.Users.DeleteObject(user);
_context.SaveChanges();
return "";
}
catch (Exception e)
{
return e.Message;
}
}
public string UpdateUser(User user)
{
try
{
if (user == null) throw new ArgumentNullException("user");
User oldUser = _context.Users.FirstOrDefault(u => u.UserID == user.UserID);
if (oldUser != null)
{
oldUser.Name = user.Name;
oldUser.Password = user.Password;
oldUser.UserName = user.UserName;
oldUser.Email = user.Email;
oldUser.CreationDate = DateTime.Now;
}
_context.SaveChanges();
return "";
}
catch (Exception e)
{
return e.Message;
}
}
public List<Contact> GetContactsByUser(int id)
{
User user = _context.Users.FirstOrDefault(u => u.UserID == id);
if (user == null) throw new ArgumentNullException("id");
return user.Contacts.OrderBy(c=>c.Name).ToList();
}
public string AddContact(Contact contact, string userName)
{
try
{
User user = _context.Users.FirstOrDefault(u => u.UserName == userName);
if (user != null) user.Contacts.Add(contact);
_context.SaveChanges();
return "";
}
catch (Exception e)
{
return e.Message;
}
}
public string DeleteContact(int id)
{
try
{
Contact contact = _context.Contacts.FirstOrDefault(c => c.ContactID == id);
_context.Contacts.DeleteObject(contact);
_context.SaveChanges();
return "";
}
catch (Exception e)
{
return e.Message;
}
}
public string UpdateContact(Contact contact)
{
try
{
Contact oldContact = _context.Contacts.FirstOrDefault(c => c.ContactID == contact.ContactID);
if (oldContact != null)
{
oldContact.Name = contact.Name;
oldContact.PhoneNumber = contact.PhoneNumber;
oldContact.Email = contact.Email;
oldContact.Mobil = contact.Mobil;
oldContact.Address = contact.Address;
}
_context.SaveChanges();
return "";
}
catch (Exception e)
{
return e.Message;
}
}
}
}