如何在MVC4中使用CodeFirstApproach和ViewModel更新Delete方法

本文关键字:ViewModel 更新 Delete 方法 CodeFirstApproach MVC4 | 更新日期: 2023-09-27 18:27:01

嗨,我想使用代码优先的方法和mvc4中的视图模型来更新-删除过程。我创建了视图,并使用代码优先方法和ViewModel来插入过程,因为我的DB是完全规范化的,我使用了EF。所以我使用了代码优先的方式和ViewModel。现在我完成插入过程。现在我想知道如何使用代码优先方法和ViewModel执行UpdateDelete过程。请任何人给我答案。。

我的型号

 public class CustomerModel1
    {
        public System.Guid CustomerID { get; set; }
        public string DisplayName { get; set; }
        public string PrintName { get; set; }
 }
public partial class ContactModel
    {
        public System.Guid ContactID { get; set; }
        public string DisplayName { get; set; }
        public string PrintName { get; set; }
        public string Mobile1 { get; set; }
        public string Mobile2 { get; set; }
        public string Phone1 { get; set; }
        public string Phone2 { get; set; }
        public string Email1 { get; set; }
         public string Website1 { get; set; }
}

我的VieModel

  public class CustomerViewModel
{
  public System.Guid CustomerID { get; set; }
    public string CustomerName { get; set; }
    public System.Guid ContactID { get; set; }
    public string ContactPerson { get; set; }
    public string PhoneNo1 { get; set; }
    public string PhoneNo2 { get; set; }
    public string MobileNo1 { get; set; }
    public string MobileNo2 { get; set; }
    public string Website1 { get; set; }
 }
  public class VisitorsEntities1 : DbContext
{
 public DbSet Customer    { get; set; }
 public DbSet Contact { get; set; }
}

我的控制器

  public ActionResult Create()
    {
  return View();
    }
    [HttpPost]
 public ActionResult Create(CustomerViewModel viewmodel)
  {
     var Customerobj = new Customer()
        { 
         CustomerID= Guid .NewGuid (),
         DisplayName = viewmodel.CustomerName,
         PrintName = viewmodel .CustomerName
   };
    var Contactobj = new Contact()
        {
            ContactID= Guid.NewGuid(),
            DisplayName= viewmodel.CustomerName,
            PrintName=viewmodel.CustomerName,
            Mobile1=viewmodel.MobileNo1,
            Mobile2 = viewmodel.MobileNo2,
            Phone1= viewmodel.PhoneNo1,
            Phone2=viewmodel.PhoneNo2,
            Email1=viewmodel.Email1,
            Website1=viewmodel.Website1
            db.Customer.Add(Customerobj);
            db.Contact.Add(Contactobj);
            db.SaveChanges();
       return View();
   }

在这里,我使用CodeFirstApproachViewModel完成插入过程。插入工作正常。现在我想做更新,删除和详细信息(索引)过程。如何使用代码优先的方法和ViewModel。。。

感谢

如何在MVC4中使用CodeFirstApproach和ViewModel更新Delete方法

您只需要创建一个将模型作为参数的Update操作,并保存更改:

db.Entry(contact).State = EntityState.Modified;
db.SaveChanges();

然后添加一个Delete操作,该操作将项目的id作为参数并删除:

 Contact contact = db.Contacts.Find(id);
 db.BlogPosts.Remove(contact);
 db.SaveChanges();

实际上,如果您使用的是Visual Studio,它应该能够自动为您生成所有这些操作,然后您可以根据需要进行修改。