废话不多说 贴代码,求教各路大神帮忙解答
[Table("Student",Schema="dbo")] public class StudentDetail { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Name { get; set; } } [Table("Course", Schema = "dbo")] public class CourseDetail : StudentDetail { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int CourseId { set; get; } public string CourseName { set; get; } } [Table("Adress", Schema = "dbo")] public class AdressDetail : StudentDetail { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int AdressId { get; set; } public string AdressName { get; set; } }
using (var context = new EF6RecipesContext()) { var student = new StudentDetail { Name="王小儿"}; context.StudentDetail.Add(student); var course = new CourseDetail { CourseName="大学英语"}; context.StudentDetail.Add(course); var address = new AdressDetail { AdressName="河北省1"}; context.StudentDetail.Add(address); address = new AdressDetail { AdressName = "河北省2" }; context.StudentDetail.Add(address); address = new AdressDetail { AdressName = "河北省3" }; context.StudentDetail.Add(address); context.SaveChanges(); foreach (var o in context.StudentDetail) { Console.WriteLine("学号:{0},姓名:{1}",o.Id,o.Name); } foreach (var o in context.StudentDetail.OfType<CourseDetail>()) { Console.WriteLine("学号:{0},姓名:{1},课程:{2}", o.Id, o.Name,o.CourseName); } foreach (var o in context.StudentDetail.OfType<AdressDetail>()) { Console.WriteLine("学号:{0},姓名:{1},地址:{2}", o.Id, o.Name, o.AdressName); } }
结果如下,为什么子表插入一条数据,student表就插入数据
代码参考的地址http://www.cnblogs.com/VolcanoCloud/p/4489925.html