[英]How to do update Delete method using CodeFirstApproach and ViewModel in MVC4?
嗨,我想在mvc4中使用Code First方法和视图模型进行更新删除过程。我创建了视图,并使用Code First方法和ViewModel完成了插入过程,因为我的数据库已完全标准化并且我使用了EF。方法和ViewModel。 现在,我完成了插入过程 。 现在,我想知道如何使用Code First方法和ViewModel进行更新和删除过程。 请任何人给我解决方案。
我的模特
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; }
}
我的模特
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();
}
在这里,我使用CodeFirstApproach和ViewModel完成插入过程。 插入工作正常。 现在,我要执行更新,删除和详细信息(索引)过程。 如何使用代码优先方法和ViewModel ...
谢谢
您只需要创建一个将模型作为参数的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,它应该能够自动为您生成所有这些操作,然后您可以根据需要进行修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.