[英]Not adding data to SQL database through Entity Framework model C#
This question might be asked but I could not find the answer for now so please help me with this. 可能会问这个问题,但我暂时找不到答案,请为此提供帮助。 I'm trying to add a new row into my SQL database through EF model.
我正在尝试通过EF模型将新行添加到SQL数据库中。 Is there anything wrong because it looks okay but actually does not insert anything to the table.
有什么问题吗,因为它看起来还不错,但实际上没有在表中插入任何内容。
private void Bsubmit_Click(object sender, EventArgs e)
{
using(var db = new Models.CompanyDBEntities())
{
db.Clients.Add(new Client
{
name = nameTB.Text,
age = Convert.ToInt32(ageTB.Text)
});
db.SaveChanges();
}
}
EDIT** So now I'm adding a Change Tracker to see what's going on: 编辑**所以现在我要添加一个变更跟踪器以查看发生了什么:
if (db.ChangeTracker.HasChanges()){
db.SaveChanges();
var clients = (from c in db.Clients select c).ToList();
string updated = "";
foreach (var c in clients)
{
updated += c.Name;
}
MessageBox.Show(updated);
}
The message box does show up the name of current clients in the data together with the name I just added. 该消息框的确会在数据中显示当前客户端的名称以及我刚刚添加的名称。 I think the problem here is .SaveChanges() it's not working.
我认为这里的问题是.SaveChanges()无法正常工作。 I did not find the solution yet.
我尚未找到解决方案。
Try add Parameterless Constructor to your class and try again, just guess: 尝试将无参数构造函数添加到您的类中,然后重试,只需猜测:
public class Client
{
public Client()
{
}
public string name ...
public int age ...
...
}
and use parentheses when new: 'new Client () {' 并在新的时候使用括号:'new Client () {'
db.Clients.Add(new Client()
{
name = nameTB.Text,
age = Convert.ToInt32(ageTB.Text)
});
尝试运行Sql Server Profiler ,并检查针对您的语句执行的查询,很可能您会找到答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.