Теперь я думаю, что у нас есть вся информация, чтобы обозначить проблемы, с которыми вы столкнулись Суть в том, что ограничения внешнего ключа (FK) работают не так, как, я думаю, вы их понимаете. Ограничения FK - это просто «правила», которым должны соответствовать данные в вашей базе данных. Ограничения FK не не вводят никакой автоматизации, например, добавление строки в Table2
только потому, что вы вставили что-то в Table1
. Это что-то , что вам нужно сделать явно .
Для решения вашей проблемы:
Отношения между вашими таблицами следующие (на основе содержимого файла EDMX, которое вы разместили) :
TableA | Cardinality | TableB
------------------------------------------------
customer | 1 <--> 0..* | dishesranking
dishes | 1 <--> 0..* | dishesranking
customer | 1 <--> 0..1 | customerpreferences
order | 1 <--> 0..* | customerpreferences
type_dishes | 1 <--> 0..* | customerpreferences
order | 1 <--> 0..* | dishes
restaraunt | 1 <--> 0..* | dishes
dishes | 1 <--> 0..* | ingridients
customer | 1 <--> 0..* | order
restaraunt | 1 <--> 0..* | order
dishes | 1 <--> 0..* | type_dishes
В настоящее время вы можете без проблем вставить данные в таблицу customer
, и вы показали, что данные отображаются в базе данных в этой таблице, например, на вашем первом изображении. Здесь нет проблем. Это связано с тем, что, как показано в приведенной выше таблице, строка в таблице customer
не требует каких-либо данных в других таблицах (правая часть количества элементов допускает "0" для всех других таблиц).
Однако , если вы хотите вставить что-то в customerpreferences
, тогда вам нужно иметь что-то в customer
, order
и type_dishes
. Например, order | 1 <--> 0..* | customerpreferences
означает, что для каждого customerpreferences
должно быть order
.
. Все вышеперечисленное является определением ограничения FK. Это просто правила - никакой автоматизации не требуется.
Теперь ... вы ожидаете, что поскольку вы вставляете что-то в customer
, вы ожидаете, что что-то будет вставлено и в customerpreference
. Это не то, как работает ограничение FK. Вам нужно вставить что-то вручную в customerpreference
. Однако, поскольку customerpreference
имеет другие ограничения FK, как вы можете видеть из количества элементов выше, вам также необходимо вставить что-то в order
и type_dishes
, прежде чем вы сможете вставить что-либо в customerpreference
. Как видно из моей таблицы, этот шаблон продолжается: чтобы вставить что-либо в order
, вам нужно иметь что-то в customer
и restaraunt
... и т. Д.
Как вставить данные
Я не собираюсь приводить вам полный пример кода, потому что у вас слишком много ограничений FK между вашими таблицами, чтобы я мог привести небольшой пример. Однако, чтобы вставить данные в базу данных, вам нужно сделать это в следующем порядке:
- Вставить
restaraunt
(rest1
) - Вставить
customer
(cust1
) - Вставка
order
(ord1
), где: ord1.Id_Cus = cust1.Id_Cus
ord1.Id_Res = rest1.Id_Res
- Вставка
dishes
(dish1
), где: dish1.Number_Ord = ord1.Number_Ord
dish1.Id_Res = rest1.Id_Res
- Вставка
type_dishes
(typDish1
), где: typDish1.Id_Dis = dish1.Id_Dis
- Вставка
customerpreferences
(custPref1
), где: custPref1.Id_Cus = cust1.Id_Cus
custPref1.Number_Ord = ord1.Number_Ord
custPref1.Id_Type = typDish1.Id_Type
До выполнения шага 1-5 невозможно вставить что-либо в customerpreferences
, поскольку ограничения FK для customerpreferences
требуют, чтобы что-то уже существовало в customer
, dishes
и type_dishes
(см. таблицу количества элементов). Если вы попытаетесь вставить что-либо в customerpreferences
до шага 6, вы увидите ошибку (или аналогичную), описанную вами в комментариях:
System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
MySqlException: Cannot add or update a child row: a foreign key constraint fails (chik-chak. Custompreferences, CONSTRAINT fk_CustomerPreferences_Order1` FOREIGN KEY (Id_Res) REFERENCES` order` (Number_Ord))
Эта указанная ошибка c говорит о том, что вы не может вставить что-либо в customerpreference
без установки customerpreference.Number_Ord
идентификатора, сопоставляющего элемент в таблице order
.
Сводка
Как видно из приведенного выше у вас довольно сложная настройка ограничений FK в вашей базе данных, и я бы настоятельно рекомендовал прочитать и понять, как работают ограничения внешнего ключа, прежде чем продолжить работу над проектом. Это также означает, что вы должны понимать, как вставлять данные с помощью простых команд SQL в базе данных, прежде чем работать с этим в Entity Framework (EF). Это даст вам гораздо лучшее понимание, которое трудно получить при работе только с EF, потому что EF скрывает некоторые из этих деталей - это то, что делает EF блестящим, но в то же время может затруднить понимание реляционных баз данных, если вы новичок в ит.
Старый ответ:
### My understanding of your question:
> This function creates a customer in the first table. The first and second table are connected by the primary key (Id_Cus), so when I create the first table Id_Cus should be automatically imported into the second table (for this I used eager loading with Include method). When this function is executed, no errors occur and everything is created correctly in the first table, however (Id_Cus) is not imported into the second table (it is completely empty).
If I understand correctly from your comment, you have two tables defined somewhat like this:
**EDIT:** you have added your own database models in your question so I've removed my examples here.
What you're trying to do is to read an entity from the `customer` table and include that customer's preferences from the `customerpreferences` table, so you can see it in the navigation property `c.customerpreference` - correct me if I'm wrong.
---
In your example, you are never adding/saving anything to the `customerpreference` table. What you need is to create a `customerpreferences` along with you `customer`. This could be done in two ways to ensure there's a relationship between the two tables
### Example 1
-```
public void InsertCustomer(customer customerDataContract)
{
customer cust = new customer()
{
Id_Cus = customerDataContract.Id_Cus,
FirstName_Cus = customerDataContract.FirstName_Cus,
LastName_Cus = customerDataContract.LastName_Cus,
PhoneNum_Cus = customerDataContract.PhoneNum_Cus,
Email_Cus = customerDataContract.Email_Cus,
customerpreference = new customerpreference()
{
Id_Cus = customerDataContract.Id_Cus
Id_Res = x, // some value
Name_Dis = y, // some value
Id_Type = z // some value
}
};
// EF knows that cust.customerpreference should be saved in
// the customerpreferences table
dc.customers.Add(cust);
dc.SaveChanges();
customer custFromDb =
(from n in dc.customers
where n.Id_Cus == k
select n)
.Include(c => c.customerpreference)
.First();
// custFromDb.customerpreference should no longer be null
}
-```
### Example 2
-```
public void InsertCustomer(customer customerDataContract)
{
customer cust = new customer()
{
Id_Cus = customerDataContract.Id_Cus,
FirstName_Cus = customerDataContract.FirstName_Cus,
LastName_Cus = customerDataContract.LastName_Cus,
PhoneNum_Cus = customerDataContract.PhoneNum_Cus,
Email_Cus = customerDataContract.Email_Cus
};
dc.customers.Add(cust);
customerpreference custPref = new customerpreference()
{
Id_Cus = customerDataContract.Id_Cus
Id_Res = x, // some value
Name_Dis = y, // some value
Id_Type = z // some value
};
dc.customerpreferences.Add(custPref);
// Now the entities are saved separately in each table
dc.SaveChanges();
customer custFromDb =
(from n in dc.customers
where n.Id_Cus == k
select n)
.Include(c => c.customerpreference)
.First();
// custFromDb.customerpreference should no longer be null
}
-```