Entity Framework 6 Code First Tutorial
Entity Framework 6 Code First Tutorial , enjoy
public class User
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public List<Article> Articles { get; set; }
}
public class Article
{
[Key]
public int Id { get; set; }
public int ArticleId { get; set; }
[ForeignKey("User")]
public int UserIdFK { get; set; }
public virtual User User { get; set; }
public int NumOfClicks { get; set; }
}
public class MyDb : DbContext
{
public MyDb()
: base("name=MyDb")
{
}
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Article> Articles { get; set; }
}
public static void AddUser()
{
using (var db = GetDataBase())
{
db.Users.Add(new User() { Name = "Coding is Simple" });
db.SaveChanges();
}
}
public static User GetUser(int userId)
{
using (var db = GetDataBase())
{
return db.Users.Where(x => x.Id == userId).FirstOrDefault();
}
}
public static void UpdateUser1(int userId)
{
using (var db = GetDataBase())
{
var u = db.Users.Where(x => x.Id == userId).FirstOrDefault();
u.Name = "Wow";
db.SaveChanges();
}
}
public static void UpdateUser2(int userId)
{
using (var db = GetDataBase())
{
User a = new User() { Id = userId, Name = "Wow" };
db.Users.Attach(a);
db.Entry(a).Property(c => c.Name).IsModified = true;
db.SaveChanges();
}
}
public static void DeleteUser(int userId)
{
using (var db = GetDataBase())
{
var articles = db.Articles.Where(x => x.UserIdFK == userId).ToList();
for (int i = 0; i < articles.Count; i++)
{
db.Articles.Remove(articles[i]);
}
db.Users.Remove(GetUser(userId));
db.SaveChanges();
}
}
public static MyDb GetDataBase()
{
return new MyDb();
}