简体   繁体   中英

c# Error as threw an exception of type 'System.Data.Entity.Core.EntityCommandExecutionException'

Please help me. How can I remove that Error?

Here I have two classes:

 public class Users
    {
        public int UserId { get; set; } 
       public int RoleId { get; set; }
        public String Username { get; set; }
        public virtual ICollection<Role> Roles { get; set; }
}
public class Role
    {
        public int RoleId { get; set; }
        public string RoleName { get; set; }  
        public virtual ICollection<Users> Users { get; set; }
    }

Here i wrote Simple Linq Query for Finding Result

 enum TypeofEmp{
                Admin=100,
                HttpRequest=101,
                Devoloper=102
        };
         public Users GetUsers(string Uname, string psw)
                {

                    var x = (from n in db.Users
                            where n.Username == Uname && n.Password == psw
                            select n).FirstOrDefault();
                    if(x!=null){
                ICollection<Role> role = new List<Role>();

                        int RoleId = x.RoleId;
                var RoleNmae   =  Enum.GetName(typeof(TypeofEmp), RoleId);    
                Role dd = new Role(); dd.RoleId = RoleId;  dd.RoleName = RoleNmae;
 Users users = new Users();
                users.Roles = role;
                    }       
                    return x;

Here i'm Getting Error as

'x.Roles' threw an exception of type 'System.Data.Entity.Core.EntityCommandExecutionException'

You are trying to access Users.RoleId property, but that does not exist. You only have a Roles property, which has a list of roles (meaning one user may have multiple roles assigned).

foreach ( var role in x.Roles )
{
   //do something with role.RoleId
} 

As a tip, I would rename the Users class o User , because now it is quite confusing, as you refer to a single user as Users .

Also, in the code you are creating dd variable with the role instance, but you are not using it anywhere. I am not sure this is what you want.

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