2011-08-29 15 views
8

Actualmente tengo una entidad que estoy tratando de editar a través de mi aplicación web MVC 3. Recibo un DbUpdateConcurrencyException cuando intento realizar un acercamiento de victorias del cliente que recibí de la publicación Using DbContext in EF 4.1 Part 9: Optimistic Concurrency Patterns de MSDN. Lo extraño es que esto solo sucede en esta entidad en particular y no estoy haciendo nada diferente de la otra. Además, solo ocurre cuando se actualiza desde un valor nulo a uno. Las propiedades que dan el error cuando se actualiza desde un valor nulo a un valor de DateTime son DispositionLetterDate y DateDisposition.Entity Framework 4.1 - Primero el código - No se puede actualizar nullabe DateTime valores al resolver DbUpdateConcurrencyException

Clase:

public class A22 
{ 
    public A22() 
    { 
     this.IsArchived = false; 
     this.A22StatusId = (int)AStatus.Open; 
    } 

    [Key] 
    public int Id { get; set; } 

    [Required] 
    [StringLength(100, ErrorMessage="A22 Number cannot exceed 100 characters")] 
    public string Number { get; set; } 

    [Display(Name="Manual")] 
    public int ManualId { get; set; } 

    [Display(Name="SGMLID")] 
    public string SGMLId { get; set; } 

    [Required] 
    [DataType(DataType.Date)] 
    [Display(Name="Date Received")] 
    public DateTime DateReceived { get; set; } 

    [Display(Name= "Status")] 
    [EnumDataType(typeof(A22Status))] 
    public int A22StatusId { get; set; } 

    [Display(Name="Priority")] 
    [EnumDataType(typeof(A22Priority))] 
    public int A22PriorityId { get; set; } 

    [Display(Name="Providing Disposition")] 
    public string ProvidingDisposition { get; set; } 

    [Display(Name="Final Disposition")] 
    public bool FinalDisposition { get; set; } 

    [Display(Name="Is Archived")] 
    public bool IsArchived { get; set; } 

    [Display(Name="Created By")] 
    public int CreatedById { get; set; } 

    [Display(Name="Date Created")] 
    public DateTime DateCreated { get; set; } 

    [ConcurrencyCheck] 
    [Display(Name="Date Modified")] 
    public DateTime DateModified { get; set; } 

    [Display(Name = "Disposition Date")] 
    public DateTime? DateDisposition { get; set; } 

    [Display(Name = "Date Disposition Letter Sent")] 
    public DateTime? DispositionLetterDate{ get; set; } 

    // Virtual Properties 

    [ForeignKey("CreatedById")] 
    public virtual User CreatedBy { get; set; } 

    [ForeignKey("ManualId")] 
    public virtual Manual Manual { get; set; } 

    public virtual ICollection<A22Manual> A22ManualsImpacted { get; set; } 

    public virtual ICollection<A22Task> A22TasksImpacted { get; set; } 

    public virtual ICollection<A22Comment> Comments { get; set; } 

    public virtual ICollection<A22HistoryLog> HistoryLogs { get; set; } 
} 

controlador:

[HttpPost] 
public ActionResult Edit(A22 a22) 
{ 
    var d = new A22Repository().Find(a22.Id); 
    var changes = TrackChanges(d, a22); 
    if (ModelState.IsValid) { 
     if (!string.IsNullOrEmpty(changes)) 
     { 
      repository.InsertOrUpdate(a22); 
      this.repository.AddHistory(a22, changes); 
      repository.Save(); 
     } 
     return RedirectToAction("Details", new { id = a22.Id }); 
    } else { 
     ViewBag.PossibleManuals = d.ManualId == default(int) ? manualRepo.GetManualList() : 
                   manualRepo.GetManualList(d.ManualId); 
     ViewBag.APriority = repository.GetAPriorityList(d.APriorityId); 
     ViewBag.AStatus = repository.GetAStatusList(d.APriorityId); 
     return View(); 
     } 
    } 
} 

Vista:

@model TPMVC.Web.Models.A22 

@{ 
    Layout = "~/Views/Shared/_BlendLayoutLeftOnly.cshtml"; 
    ViewBag.Title = "Edit"; 
} 

<h2>Edit A22# @Model.Number</h2> 

@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary(true) 
    @Html.HiddenFor(model => model.Id) 
    @Html.HiddenFor(model => model.CreatedById) 
    @Html.HiddenFor(model => model.DateCreated) 
    @Html.HiddenFor(model => model.DateModified) 
    @Html.Partial("_CreateOrEdit") 

    <div class="newItemLabel"> 
     <strong style="padding-right: 145px;">@Html.LabelFor(model => model.AStatusId)</strong> 
    @{ 
     Html.Telerik().DropDownList() 
      .Name("AStatusId") 
      .BindTo((IEnumerable<SelectListItem>)ViewBag.AStatus) 
      .HtmlAttributes(new { @style = "width: 200px;" }) 
      .Render(); 
    } 
     @Html.ValidationMessageFor(model => model.AStatusId) 
    </div> 

    <div class="newItemLabel"> 
     <strong style="padding-right: 77px;">@Html.LabelFor(model => model.FinalDisposition)</strong> 
     @Html.EditorFor(model => model.FinalDisposition) 
    </div> 

    <div class="newItemLabel"> 
     <strong style="padding-right: 44px;">@Html.LabelFor(model => model.DateDisposition)</strong> 
     @{ 
      Html.Telerik().DatePickerFor(model => model.DateDisposition) 
      .Render();  
     } 
    </div> 

    <div class="newItemLabel"> 
     <strong style="padding-right: 44px;">@Html.LabelFor(model => model.DispositionLetterDate)</strong> 
     @{ 
      Html.Telerik().DatePickerFor(model => model.DispositionLetterDate) 
      .Render();  
     } 
    </div> 

    <div class="newItemLabel"> 
     <strong style="padding-right: 110px;">@Html.LabelFor(model => model.IsArchived)  </strong> 
     @Html.EditorFor(model => model.IsArchived) 
    </div> 

    <p> 
     <input type="submit" value="Save" /> 
    </p> 

} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

Pensando que era podría haber sido algo con las anotaciones de datos, decidí definir las propiedades con este problema es opcional con la API Fluid.

modelBuilder.Entity<A22>().Property(a => a.DateDisposition).IsOptional(); 
modelBuilder.Entity<A22>().Property(a => a.DispositionLetterDate).IsOptional(); 

Básicamente necesito un nuevo par de ojos para ver si me falta algo. ¿Hay alguna otra propiedad que lo está haciendo comportarse de esta manera?

Gracias de antemano.

+0

¿En qué base de datos está asignada su configuración de EF? MS SQL Server, MySQL, ¿algo más? – Regfor

+0

Hay un error que tiene que ver con la actualización de una propiedad que admite valores nulos desde nulo hasta un valor. Si publica el código de InsertOrUpdate, puedo decirle si lo está o no. – cadrell0

Respuesta

1

Estoy mapeando propiedades de DateTime nullable como las siguientes sin métodos IsOptional. También funciona bien con MS SQL y MySQL por mí.

this.Property(t => t.CreatedDate).HasColumnName("CreatedDate"); 
this.Property(t => t.ModifiedDate).HasColumnName("ModifiedDate"); 

en clase derivado de EntityTypeConfiguration. Estoy usando el enfoque Code First.

Cuestiones relacionadas