[英]C# How to insert/update the parent and child data to the sql database using entity framework in asp.net mvc
I'm developing a website using asp.net mvc 5 and the database that I'm using is MS SQL Server Management Studio 17. Right now I want to insert and update some data with parent and child relationship to the database using entity framework in one shot. 我正在使用asp.net mvc 5开发一个网站,而我正在使用的数据库是MS SQL Server Management Studio17。现在,我想使用中的实体框架向数据库插入和更新具有父子关系的数据。一枪。
The parent table(Accounts): 父表(帐户):
public class Accounts
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
//The foreign key in database
public int UserAddressId { get; set; }
//The child collection
public virtual ICollection<Addresses> Addresses { get; set; }
}
The child table(Address): 子表(地址):
public class Addresses
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int AddressId { get; set; }
[ForeignKey("AddressId")]
public virtual Accounts Account { get; set; }
}
I know in sql if I want to insert data into the parent table, I have to create the data for the child table first, and then insert data the data to the parent table. 我知道在sql中是否要将数据插入父表中,我必须先为子表创建数据,然后再将数据插入父表中。 However, I don't know how to do it in entity framework. 但是,我不知道如何在实体框架中执行此操作。
Question 1: Am I setting up the relationship in the entity classes correctly? 问题1:我是否在实体类中正确设置了关系?
Question 2: How do I insert/update the data to the database using entity framework? 问题2:如何使用实体框架向数据库插入/更新数据? I want to do it in one shot, please provide me some code examples. 我想一次性完成,请提供一些代码示例。
Models: 楷模:
public class Account
{
public int AccountId { get; set; }
public virtual ICollection<Addresses> Addresses { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public int AccountId { get; set; }
public virtual Account Account { get; set; }
}
DbContext: DbContext:
public partial class ApplicationDbContext: DbContext
{
public AppContext(): base("name=ApplicationDbContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
public virtual DbSet<Account> Accounts { get; set; }
public virtual DbSet<Address> Addresses { get; set; }
}
Controller: 控制器:
public class HomeController : Controller
{
public ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
...
}
Then take a look this article for add and update operations. 然后看一下这篇文章,了解添加和更新操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.