Can someone give me any help with this problem:
I have a database built with entity framework. In my simple project, all I'm trying to do is to add a new row in the database, that's all.
I have one class for the database, named UserDB
public class UserDB : DbContext
{
public UserDB()
: base("UserDB")
{
}
public List<User> Users { get; set; }
}
and class for the User
[Table(Name="User")]
public class User
{
[Key]
public String Name { get; set; }
}
I'm trying to add a new data in the database with another Console application, but every time I invoke the method insertInformation(string name) it says that the List of Users in UsersDB is null, and can't add the new User in the database. I used the same method in other ASP.NET application and it all work perfect. If someone have idea how to solve this, please help
The service I'm using:
public class Service1 : IService1
{
/// <summary>
/// Method for adding new User in Database
/// </summary>
/// <param name="name"></param>
public void insertData(string name)
{
UserDB db = new UserDB();
User user = new User
{
Name = name
};
//if (db.Users == null)
//{
// db.Users = new List<User>();
// db.Users.Add(user);
//}
//else
// db.Users.Add(user);
db.Users.Add(user);
db.SaveChanges();
}
Maybe you should try using the following code:
Instead of:
List<User> Users { get; set; }
Simply try:
DbSet<User> Users { get; set; }
I always use DbSet or IDbSet in my DBContext's and it always works.
Use this
db.Users.InsertAllOnSubmit(user);
db.SubmitChanges();
Instead of
db.Users.Add(user);
db.SaveChanges();
try this
db.AddObject("User", user);
db.SaveChanges();
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.