问题
My persons class:
public class User
{
public int Id { get; private set; }
public string Isim { get; set; }
public string Soyad { get; set; }
public User(string isim, string soyad)
{
Isim = isim;
Soyad = soyad;
}
}
My UserBusiness class:
public sealed class UserBusiness
{
JuqueryDbEntities entity = new JuqueryDbEntities();
private static volatile UserBusiness instance;
private static readonly object syncRoot = new Object();
private UserBusiness() { }
public static UserBusiness Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new UserBusiness();
}
}
return instance;
}
}
public void AddUser(User userToAdd)
{
entity.PersonelTable.Add(userToAdd);
entity.SaveChanges();
}
}
And lastly my webform codebehind onclick of a login button:
protected void Button1_Click(object sender, EventArgs e)
{
string isim = TextBox1.Text;
string soyad = TextBox2.Text;
var newUser = new User(isim, soyad);
UserBusiness.Instance.AddUser(newUser);
}
Here is my problem: I get an error in AddUser method of my UserBusiness class. An error in 'entity.PersonelTable.Add(newUser);' line says 'The best overload method match for 'System.Data.Entity.DbSet.Add(SuperQquery.PersonelTable)' has some invalid arguments.' What am I doing wrong(Btw my Id is autoincrement so I am not setting it any value.)
回答1:
your problem here is that the method Add
of System.Data.Entity.DbSet
does simply not take argument of type user.
like mentioned in the error
System.Data.Entity.DbSet.Add(SuperQquery.PersonelTable)' has some invalid arguments
it takes objects of type SuperQquery.PersonelTable
So what you need to do is change AddUser method
public void AddUser(User userToAdd)
{
SuperQquery.PersonelTable pt = new SuperQquery.PersonelTable();
pt.FieldName1 = userToAdd.Isim;
pt.FieldName2 = userToAdd.Soyad;
entity.PersonelTable.Add(pt);
entity.SaveChanges();
}
where FieldName are names of columns in the table of the database
EDIT: if this works, we can say that you made a conversion of type user to type SuperQquery.PersonelTable the way you can insert data in database, but the best way here is to change the class User by a new class PersonelTable with the same logic. No need to do a conversion.
来源:https://stackoverflow.com/questions/36747614/entity-framework-cant-add-with-singleton