简体   繁体   中英

mscorlib:System.reflection.TargetInvocationException

I'm working on c# project with Entity Framework try to get object from the FirstOrDefault or Find method from context.

I got this error in C# Entity Framework

that's my code

private void btn_login_Click(object sender, EventArgs e)
    {
        String pass = textBox_password.Text.ToString();
        String strid = textBox_userName.Text.ToString();

        try
        {
            int id = Convert.ToInt32(strid);
            User user;
            DbContextDal dal = new DbContextDal();

            user = dal.users.Find(id); // crash here 
            // user = dal.users.FirstOrDefault(x => x.ID == id); // also crash here 

            if (user == null)
            {
                return;
            }
            // Pass OK, find user or return null object
        }           
        catch (Exception ex)
        {
            string str = "" + ex.Source + " : " + ex.GetType() + "\n" +
                          "Message: " + ex.Message;
            MessageBox.Show(str);
        }

    }

in this lines

DbContextDal dal = new DbContextDal();
            user = dal.users.Find(id);

it crash and throw exception message:

mscorlib : System.reflection.TargetInvocationException Message : Exception has been throw by the target of an invocation

even I wrote this line instead

   user = dal.users.FirstOrDefault(x => x.ID == id);

that's my User code

public class User
{

    private int _UserID;
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Column(Order = 1)]
    public int ID
    {
        get { return _UserID; }
        set
        {
            if (value != _UserID)
            {
                _UserID = value;
            }
        }
    }

    [Required]
    [StringLength(25)]
    public string password { get; set; }
    [Required]
    [RegularExpression("Secretary|Admin|Lecturer|Practitioner|Student|StudentSchedule")]
    public string permission { get; set; }

    public User(int id, string _permission)
    {
        ID = id;
        password = "0000";
        permission = _permission;
    }

    public User(int id, string _password, string _permission)
    {
        ID = id;
        password = _password;
        permission = _permission;
    }
}

the answer is , missed default constructor !!

dont know how to do it without default constructor , but in that way if work for you

do: public User(){}

in your user class.

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