简体   繁体   中英

Why is Entity Framework not saving enum properties on my model properly?

Here is my model with their related enums below which I am using with entity framework 5 and asp.net mvc4 codefirst. I am also using portable database file(.mdf)

public class Project
    {
        public Project()
        {
            Images = new List<ProjectImage>();
        }

        public int ProjectId { get; set; }
        [Required]
        public string Title { get; set; }
        public virtual ICollection<ProjectImage> Images { get; set; }
        public string Description { get; set; }
        public ProjectType Type { get; set; }
        public ProjectState State { get; set; }
    }

    public enum ProjectType
    {
        Phone,
        Web,
        Windows
    }

    public enum ProjectState : byte
    {
        InProgress,
        NotStarted,
        Done
    }

After posting back the model from a view, all the fields get saved to the database properly except the enum fields. They get saved but will only save the first values of each enum type even after selecting different values in the view.

I have tried saving edits as well and the same happens.

I have stepped through the beginning of my create post method and all seems ok after calling savechanges on my context but when I redirect back to the index page, it shows the enum property values as the initial ones on the enums( ie the first enum values)

My create and edit methods are below. Hopefully its not a bug but please help as I have been pulling my hair out for couple of days with this. I'm just starting out with codefirst and enums together. Thanks.

Create post Method

[HttpPost]
        public ActionResult Create(Project project, HttpPostedFileBase file)
        {
            try
            {
                if (file != null && file.ContentLength > 0 && file.ContentType.Contains("image"))
                {
                    //create a new unique filename with using guid, filename and project title
                    string relativePath = Constants.PortfolioImagesBaseFolder + 
                                        project.Title.Replace(" ", "") + 
                                        Guid.NewGuid().ToString() +
                                        Path.GetFileName(file.FileName);

                    string absolutePath = Server.MapPath(relativePath);

                    //save the file
                    file.SaveAs(absolutePath);

                    if (ModelState.IsValid)
                    {
                        project.Images.Add(new ProjectImage()
                        {
                            IsProjectMainImage = true,
                            Url = relativePath,
                            Title = "Main Project Image"
                        });
                        context.Projects.Add(project);
                        context.SaveChanges();

                        return RedirectToAction("Index");
                    }
                }

                ViewBag.ProjectTypes = CreateSelectListFromEnumType<ProjectType>();

                ViewBag.ProjectStates = CreateSelectListFromEnumType<ProjectState>();

                return RedirectToAction("Index");
            }

Edit Post method

[HttpPost]
        public ActionResult Edit(int id, Project project)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Project projectFromDb = context.Projects.Single(p => p.ProjectId == id);
                    //projectFromDb.State = project.State;
                    //projectFromDb.Type = project.Type;
                    //projectFromDb.Title = project.Title;
                    //projectFromDb.Description = project.Description;
                    EntityState entityState = context.Entry(project).State;
                    context.Entry(project).State = EntityState.Modified;
                    context.SaveChanges();
                    return RedirectToAction("Index");
                }

                ViewBag.ProjectTypes = CreateSelectListFromEnumType<ProjectType>();

                ViewBag.ProjectStates = CreateSelectListFromEnumType<ProjectState>();

                return View(project);
            }

Also before marking as duplicate, I have looked at many answers on stackoverflow and none could help me, cheers, hence the wait for two days before asking the question.

As per your comments - since you targeted .NET Framework 4 the enum properties were not discovered and added to the model since EF 4 which was part of .NET Framework 4 did not support enums and the application would not work on a machine that has only .NET Framework 4 (and not the .NET Framework 4.5 which is an in-place update) installed. For the same reason EF5 installed in a project targeting .NET Framework 4 does not allow using features that are available in EF5 (enums, geo spatial types, TVFs and more) when targeting .NET Framework 4.5. Retargeting your project to .NET Framework 4.5 and reinstalling EF5 will make all these features available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM