1
我试图删除客户端记录。客户端包含一个地址,我想我在处理关系时遇到了删除顺序问题。基本上我想删除一个客户端,如果他们有一个地址,删除它。 这是完整的异常错误消息我得到:尝试删除记录时ASP.net MVC 4错误
DbUpdateException是未处理由用户代码
同时节省不为他们的关系暴露的外键 性质的实体时发生错误。 EntityEntries属性 将返回null,因为无法将单个实体标识为异常的源 。通过在您的实体类型中公开外键属性,可以更轻松地处理异常,同时保存 。有关详细信息,请参阅 InnerException。
模型
public class Address
{
[Required]
public int Id { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Street Address")]
public string StreetAddress { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Postal Code")]
public string PostalCode { get; set; }
[DataType(DataType.Text)]
public string City {get; set; }
[DataType(DataType.Text)]
public string Province {get; set;}
public virtual Clients client { get; set; }
}
public class Clients
{
[Required]
public long Id { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone ")]
public string PhoneNumber { get; set; }
public virtual Address Address {get; set;}
[Display(Name = "Email List")]
public Boolean EmailList { get; set; }
[DataType(DataType.EmailAddress)]
[Display(Name = "E-mail")]
public string Email { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Hair Type")]
public string HairType { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
}
上下文类
public class VolumeV2Context : DbContext
{
public DbSet<GiftCard> GiftCards { get; set; }
public DbSet<Clients> Clients { get; set; }
public DbSet<Address> Address { get; set; }
public DbSet<Inventory> Inventories { get; set; }
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Clients>()
.HasOptional(j => j.Address)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
/* modelBuilder.Entity<Address>()
.HasRequired(j => j.client)
.WithRequiredDependent()
.WillCascadeOnDelete(true) ;
*/
base.OnModelCreating(modelBuilder);
}
}
客户机控制器删除方法
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(long id)
{
//find the client
Clients clients = db.Clients.Find(id);
//find the address
Address address = db.Address.Find(clients.Address.Id);
// set the reference to null?
address.client = null;
//remove the address foreign key?
clients.Address = null;
//Apply to db?
db.Entry(address).CurrentValues.SetValues(address);
db.Entry(clients).CurrentValues.SetValues(clients);
db.Address.Remove(address);
//remove the client
db.Clients.Remove(clients);
//exception error happens here
db.SaveChanges();
return RedirectToAction("Index");
}
我的订单或删除有问题吗?或者我只是没有做正确的事情?我只想有能力删除有或没有地址的客户端。
plz发布内部例外,你正在删除操作 – 2013-03-06 06:29:31
抱歉。我现在发布了它 – Fpanico 2013-03-06 07:12:46
当你得到异常复制内部异常信息并发布在这里 – 2013-03-06 09:57:40