Click here to Skip to main content
15,936,565 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Good day Code Gurus, kindly assist in resolving this error :
C#
EntityType 'HttpPostedFileBase' has no key defined. Define the key for this EntityType.

I have searched online for a solution but all the recommended fixes don't solve this error. Here is the background of my problem, I recently changed my Entity Data Model from "EF Designer from Database (EDMX)" to "Code First from Database", the reason for the change came about an error I was getting when I attempted to host the system. The system couldn't connect to the database server. The hosting team recommended this change. Now I created a new project and copied the code from the old system. When I run the system I keep getting this error "EntityType: EntitySet 'HttpPostedFileBases' is based on type 'HttpPostedFileBase' that has no keys defined." see error log link. I have also uploaded this project to my google drive should you wish to take a look at the code then download it from the link provided below. I would really appreciate getting feedback from you guys, thank you for taking time out of your busy schedule to assist.

Erroneous Code
C#
public tblLogin Search(string userEmail, string userPassword)
        {
            try
            {
                userPassword = HelperFunction.PasswordEncrypt(userPassword, ConfigurationManager.AppSettings["Encyptkey"]);

                return db.tblLogins.Where(user => user.Email.Equals(userEmail) && user.UserPassword.Equals(userPassword)).FirstOrDefault();
the error is thrown here, in fact whenever I try to query the database.
            }
            catch (Exception err)
            {
                ExceptionLogger.LogException(err, "[Controller: Account] [Action Method: Search(string userEmail, string userPassword)]");

                return null;
            }
        }



Model Class
C#
[Table("tblLogin")]
    public partial class tblLogin
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public tblLogin()
        {
            tblRecordKeys = new HashSet<tblRecordKey>();
        }

        public int Id { get; set; }

        [Required]
        [StringLength(100)]
        public string Email { get; set; }

        [Required]
        [StringLength(100)]
        public string UserPassword { get; set; }

        public int RoleID { get; set; }

        public int StateID { get; set; }

        public bool Verified { get; set; }

        public Guid AuthorizationCode { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<tblRecordKey> tblRecordKeys { get; set; }

        public virtual tblState tblState { get; set; }

        public virtual tblMember tblMember { get; set; }

        public virtual tblRole tblRole { get; set; }
    }


Metadata Model Class

C#
[MetadataType(typeof(ModelLogin))]
    public partial class tblLogin
    {
        [Display(Name = "Confirm Password"), System.ComponentModel.DataAnnotations.Compare("UserPassword", ErrorMessage = "Password Confirmation And Password Do Not Match"), Required(ErrorMessage = "Password Confirmation Is Required!")]
        public string ConfirmPassword { get; set; }
    }
    public class ModelLogin
    {
        [Key, Column(Order = 0)]
        public int Id { get; set; }

        [Required(ErrorMessage = "Email Address Is Required!"), Display(Name = "Email Address")]
        [RegularExpression(@"[a-zA-Z0-9\-_~]+(\.[a-zA-Z0-9\-_~]+)*@[a-zA-Z0-9\-_~]+(\.[a-zA-Z0-9\-_~]+)*\.[a-zA-Z]{2,}", ErrorMessage = "Invalid Email Address")]
        public string Email { get; set; }

        [Display(Name = "Password"), Required(ErrorMessage = "Password Is Required!")]
        public string UserPassword { get; set; }

        public int RoleID { get; set; }

        public bool Verified { get; set; }
    }



Error Log Link : ErrorLog.txt - Google Drive[^]

What I have tried:

I have tried adding
C#
Key Attribute

Data Annotation to my models to tell EF the primary key Attribute but this is not working.
Posted
Updated 8-Dec-16 2:00am
v3
Comments
Kats2512 6-Dec-16 7:52am    
you should post up the code for your mvc model class, not the database files and expect people to know what to do or look for.

maybe if this was added you could get a better answer as to what your problem is exactly.
Admire Mhlaba 6-Dec-16 7:52am    
Thank you, I will do so.

I managed to fix the problem, here is the solution just in case someone out there encounters a similar problem.

When using Code First Approach All properties added to the model that are not coming from the tables should be decorated with [NotMapped ] Data Annotation Attribute, since I am using code first data model, the class model fields should match database columns.



For Example:
C#
namespace Experiment.Models
{
   [MetadataType(typeof(ModelDepartment))]
   public partial class tblDepartment
   { 
      [
         NotMapped,
         Required,
         StringLength(50)
      ]

      public string DepBuilding { get; set; }

      [NotMapped]
      public HttpPostedFile UploadedFile { get; set; }
   }

   internal sealed class ModelDepartment
   {
      public int Id { get; set; }

      [Required]
      [StringLength(50)]
      public string DepName { get; set; }

      [Required]
      [StringLength(50)]
      public string DepHOD { get; set; }
   }
}
 
Share this answer
 
v2
That's an Entity Framework error, not ASP.NET or MVC.

You simply didn't define a key field in a class called "HttpPostedFildBase". All table classes used by Entity Framework must have a key field either called "Id" or "<classname>Id".

Entity Framework is based on tons of conventions so I highly suggest you pickup a book on EF and work through it to understand how these conventions work.
 
Share this answer
 
Comments
Admire Mhlaba 6-Dec-16 9:23am    
Good day, thank you for response but HttpPostedFildBase is an Abstract Class within System.Web namespace used to store stream data. I can not modify that class. I have added the Attribute [Key] to my primary key field but this doesn't solve the problem.
Dave Kreskowiak 6-Dec-16 9:59am    
You've written something very wrong then. What does your DbContext class look like? The one that defines all the DbSet items...
Admire Mhlaba 6-Dec-16 10:16am    
Actually that is the exception message I'm getting from my error log file. Here is the link to download the DBContext Class: https://drive.google.com/open?id=0By9xalH13y_lcUsycFBtTWJ0MFE
Dave Kreskowiak 6-Dec-16 10:37am    
I have no idea what you did. That error cannot be thrown by the highlighted line of code unless there is a configuration problem in the database context and that doesn't appear to be the case.

I'm stumped.
Admire Mhlaba 6-Dec-16 10:44am    
Funny thing is I have done this before in other projects and everything works fine. I'm also baffled. The error isn't specific enough

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900