Я попытался вставить список, содержащий несколько связанных таблиц, в базу данных, используя SqlBulkCopy
. После добавления данных в базу данных я обнаружил, что связи между таблицами больше не существуют.
Вот классы:
public class Student
{
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string phoneNumber { get; set; }
public virtual ICollection<tblStudentCourses> tblStudentCourses { get; set; }
public virtual ICollection<tblTeachers> tblStudentCourses { get; set; }
}
public class tblStudentCourses
{
public int id { get; set; }
public int studentId {get;set}
public string courseName {get;set}
}
public class tblTeachers
{
public int id { get; set; }
public int studentId {get;set}
public string teacherName {get;set}
}
List<Student> student = new List<Student>();
Это метод, который я использую для вставки списка в базу данных:
var allStudent = student.Select(x=> new {x.id,x.name,x.email,x.phoneNumber});
var studentCourses = student.SelectMany(x => x.tblStudentCourses.Select(y => new {x.id,x.studentId,x.courseName}))
Для каждого из приведенных выше запросов я называю это SqlBulkCopy
расширение:
public static DataTable AsDataTable<T>(this IList<T> data)
{
DataTable dataTable = new DataTable();
PropertyDescriptorCollection propertyDescriptorCollection =
TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < propertyDescriptorCollection.Count; i++)
{
PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
Type type = propertyDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = Nullable.GetUnderlyingType(type);
dataTable.Columns.Add(propertyDescriptor.Name, type);
}
object[] values = new object[propertyDescriptorCollection.Count];
foreach (T iListItem in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
Результат в базе данных
Student :
|---------------------|------------------|------------|
| id | name | email |.....
|---------------------|------------------|------------|
| 1 | Johnny | me@me.com |
|---------------------|------------------|------------|
Course :
|---------------------|------------------|------------|
| id | studentId | courseName |
|---------------------|------------------|------------|
| 1 | 0 | JAVA |
|---------------------|------------------|------------|