5

I have been looking for an answer to this for 2 days now. I'm not even sure exactly what is wrong, but I think I may have pinpointed the possible culprit.

My program is a database tracker/manager that will keep track of the equipment at my company. The user can query for, create, and edit equipment. Right now, querying the database works, but when I try to add to or update the database the program throws Validation errors (I'll get into this more below).

I have an equipment class that has many nullable attributes (because the user may not know many of these properties when creating a new entry, we left almost all the attributes nullable) and is connected to (using foreign keys and lazy loading/"virtual") to a few other tables that were made to help normalize the database.

Here is some abreviated code to help:

Equipment Model:

public class Equipment
{
    public int EquipmentId { get; set; } //required

    public string Company { get; set; } //required

    public bool Verified { get; set; } //required

    (...other non-required attributes...)


    //The following two attributes are where my problems are I believe
    [ForeignKey("PAU")]
    public int PAUId { get; set; } //required and Foreign Key    

    //This is not required (but is FK to the related table) if the user doesn't know
    [ForeignKey("Division")]
    public Nullable<int> DivisionId { get; set; }


    //These are the lazy loading connections to the other tables in the database

    public virtual Division Division { get; set; }

    public virtual PAU PAU { get; set; }
}

Division Model: This table only contains the 5 different divisions at our company and the related IDs.

public class Division
{
    public Division()
    {
        this.Equipments = new HashSet<Equipment>();
    }

    //These are non-nullable/required fields
    public int DivisionId { get; set; }
    public string DivisionName { get; set; }

    public virtual ICollection<Equipment> Equipments { get; set; }
}

PAU Model: This model contains the PAU#s and the related description and ID.

public class PAU
{
    public PAU()
    {
        this.Equipments = new HashSet<Equipment>();
    }

    //These are non-nullable/required fields
    public int PAUId { get; set; }
    public string PAUNumber { get; set; }
    public string PAUDescription { get; set; }

    public virtual ICollection<Equipment> Equipments { get; set; }
}

Equipment Controller:

public class EquipmentController : Controller
{
    TLCP_DEVEntities4 db = new TLCP_DEVEntities4();

    (...)

    public ActionResult Edit(int id)         
    {
        ViewData["divisions"] = new SelectList(db.Equipments.
                                OrderBy(x => x.Division.DivisionName).
                                Select(x => x.Division).ToList().
                                Distinct(), "DivisionId", "DivisionName");

        ViewData["PAUNumbers"] = new SelectList(db.Equipments.
                                 OrderBy(x => x.PAU.PAUNumber).
                                 Select(x => x.PAU).ToList().
                                 Distinct(), "PAUId", "PAUNumber");

        return View(db.Equipments.Find(id)); 
    }

    [HttpPost]
    public ActionResult Edit(Equipment equipment)
    {
        if (ModelState.IsValid)
        {
            db.Entry(equipment).State = EntityState.Modified;                    
            db.SaveChanges();     //fails here                                     
            return RedirectToAction("Maintenance"); 
        }

        ViewData["divisions"] = new SelectList(db.Equipments.
                                OrderBy(x => x.Division.DivisionName).
                                Select(x => x.Division).ToList().
                                Distinct(), "DivisionId", "DivisionName");

        ViewData["PAUNumbers"] = new SelectList(db.Equipments.
                                 OrderBy(x => x.PAU.PAUNumber).
                                 Select(x => x.PAU).ToList().
                                 Distinct(), "PAUId", "PAUNumber");

        return View(equipment);
    }

    public ActionResult AddEquipment()
    {
        ViewData["divisions"] = new SelectList(db.Equipments.
                                OrderBy(x => x.Division.DivisionName).
                                Select(x => x.Division).ToList().
                                Distinct(), "DivisionId", "DivisionName");

        ViewData["PAUNumbers"] = new SelectList(db.Equipments.
                                 OrderBy(x => x.PAU.PAUNumber).
                                 Select(x => x.PAU).ToList().
                                 Distinct(), "PAUId", "PAUNumber");

        return View();
    }

    public ActionResult AddEquipment(Equipment equipment)
    {
        try
        {
            db.Equipments.Add(equipment);
            db.SaveChanges();

            return RedirectToAction("Maintenance"); 
        }
        catch (Exception ex)
        {

            ViewData["divisions"] = new SelectList(db.Equipments.
                                    OrderBy(x => x.Division.DivisionName).
                                    Select(x => x.Division).ToList().
                                    Distinct(), "DivisionId", "DivisionName");

            ViewData["PAUNumbers"] = new SelectList(db.Equipments.
                                 OrderBy(x => x.PAU.PAUNumber).
                                 Select(x => x.PAU).ToList().
                                 Distinct(), "PAUId", "PAUNumber");

            return View();
        }
    }

    (...)
}

In the views I have dropdown lists that for these attributes that are populated with the possible options already in the database (stored in ViewData above). I have tried a couple different ways of storing this data into my model, but this way seems to work the best:

<%: Html.DropDownListFor(model => model.DivisionId,
       ViewData["divisions"] as SelectList, "")%>

Ok so after a lot of debugging, the problem seems to be because the lazy loaded properties have null attributes, which are not allowed in their tables. My examples will be dealing more with creating new equipment objects, though I believe the problem is the same for editing them.

Division Example: So DivisionId in the Equipment class can be null (either user doesn't know or equipment doesn't belong to specific division), and the Equipment table/class doesn't complain about that. But when I try to SaveChanges(), the program complains becuase the virtual Division object is null (has the default DivisionId of 0 and a null DivisionName). Since Equipment.DivisionId is null, I don't want to be updating the Division table for this Equipment object. Is there a way to get around this? Should I not be lazy loading?

PAU Example: Since PAUId is a required attribute for all Equipment objects, but as in the Division Example, PAU.PAUNumber and PAU.PAUDescription are null (and PAU.PAUId is the default 0) causing an error. This is just like the first one, but with the required attribute (so I am not sure if it needs to be handled differently).

So I am not really sure how to fix this problem.

  • Is lazy loading the issue since I only want to connect my Equipment object to those other tables if the Id/Foreign Key is not null?

  • Is there some method I can call that would update the equipment object's values from the other tables based on the Id's? Is it a method that I need to create myself?

  • If I get rid of lazy loading, could you explain how I should write my queries so I can still get access to the normalized data (like DivisionName)?

I apologize for the super long post. I just didn't want to miss anything that may be important.

Edit

I have a rough solution to the PAU Example (but I don't think it works for the Division Example because of allowing nulls within Equipment but not the individual tables).

public ActionResult AddEquipment(Equipment equipment)
    {
        try
        {
            equipment.PAU.PAUId = equipment.PAUId;
            equipment.PAU.PAUNumber = db.PAUs.Find(equipment.PAUId).PAUNumber;
            equipment.PAU.PAUDescription = db.PAUs.Find(equipment.PAUId).PAUDescription;


        (...)

    }

It's not very elegant though. I tried looking at a tutorial about reflection, but it didn't really make sense. If that would be a more elegant solution, could someone try explaining that?

I'm still looking for a solution for the Division Example (since Equipment.DivisionId is nullable but Division.DivisionId is not nullable this doesn't work), so any help on either this or a more elegant solution to the above would be greatly appreciated!

9
  • And here is the error I get (it's not very helpful and when I have searched on this I haven't found an answer that fixed it): {System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at DLMP_Asset_Tracking.Controllers.EquipmentController.AddEquipment(Equipment equipment) Jun 25, 2012 at 15:27
  • What was in the EntityValidationErrors property? Jun 25, 2012 at 15:29
  • It shows that PAUId = 0 (the default, right?), and PAUDescription and PAUNumber are null (the same with Division and the 4 other properties I left out of the question due to redundancy). The ValidationErrors array shows that the null properties (PAUNumber and PAUDescription) are required, which they are by the way I have the database tables set up. Does that answer your question George? Jun 25, 2012 at 15:36
  • For PAU (since it is required), I want those values to be updated based on the PAUId of the Equipment (which is being set correctly). Would this need to be done with a method I write where I query for the PAUNumber and PAUDescription that relate to the PAUId? With the Division though, I am not sure if I can do it that way. I need to let Equipment.DivisionId be null; and if it is, I don't want to have it be connected to the Division database table. Does that make sense? I'm not sure if I'm using the write terminology, so I apologize for any confusion. Jun 25, 2012 at 15:43
  • It seems you're on the right track, though one thing you should note is that the DBEntityValidationException is typically caused by a foreign key constraint failure, not lazy loading. Depending on the version of EF you're using, you can either use the ID if known and set the value directly, or you need to use reflection to set the ID if you don't want to execute a query to look up the entity you're establishing the relationship with. Jun 25, 2012 at 16:49

1 Answer 1

0

There was a part another part of my code that was acting odd which caused the error. I appreciate all your help! Thanks!

Not the answer you're looking for? Browse other questions tagged or ask your own question.