我首先从我的Web应用程序的现有数据库项目中获得一个简单的实体框架6代码。当我保存数据时,它有效地保存,只保存了1条记录。但有时它会保存2,3个记录随机出现。
为简单起见,我有以下2个班级。一个是父母" Person"和" PersonAddress"是孩子。在我的应用程序中,1个父母总会有2个子记录。不多也不少(不要问为什么)。这是我的课程,这些课程都很简单。
List<Documento_Articulo> listaDA = lista;
listaDA.Add(new Documento_Articulo());
dgvArticulos.DataSource = null;
dgvArticulos.DataSource = listaDA;
这是我的DBContext类
[Table("Person")]
public partial class Person
{
[Key]
public int PersonID { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
[Required]
public virtual ICollection<PersonAddress> PersonAddresses { get; set; }
}
[Table("PersonAddress")]
public partial class PersonAddress
{
[Key]
public int PersonAddressID { get; set; }
public int PersonID { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
}
//示例代码
public partial class MyDBContext : DbContext
{
public MyDBContext()
: base("name=MyDBContext")
{
//skips database initialization so it wont track changes and produce error, not needed for code first
Database.SetInitializer<MyDBContext>(null);
}
public virtual DbSet<Person> Persons { get; set; }
public virtual DbSet<PersonAddress> PersonAddresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().Property(x => x.PersonID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<PersonAddress>().Property(x => x.PersonAddressID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
我做错了什么,数据总是被保存,当我保存父版本没有问题时,子记录会自动添加。但如前所述,有时会保存多组记录,但我没有看到任何原因。感谢
答案 0 :(得分:0)
试试这个:
using (var context = new MyDBContext())
{
Person.PersonAdresses.add(addres1);
Person.PersonAdresses.add(addres2);
context.Entry(Person).State=EntityState.Added;
context.SaveChanges();
};