отношение внешнего ключа - PullRequest
0 голосов
/ 13 апреля 2020

У меня есть 2 таблицы базы данных, которые связаны (первичный ключ - Id_Cus). Ниже приведена функция, которую я добавляю в базу данных клиента, при добавлении в первую таблицу она должна автоматически (Id_Cus) импортироваться во вторую таблицу. Подскажите, как правильно написать эту функцию, чтобы данные передавались?

public void InsertCustomer(customer customerDataContract)
{
        //MySQLEntities Cust = new MySQLEntities();
        customer cust = new customer();

        cust.Id_Cus = Convert.ToInt32(customerDataContract.Id_Cus);
        cust.FirstName_Cus = customerDataContract.FirstName_Cus;
        cust.LastName_Cus = customerDataContract.LastName_Cus;
        cust.PhoneNum_Cus = Convert.ToInt32(customerDataContract.PhoneNum_Cus);
        cust.Email_Cus = customerDataContract.Email_Cus;
        int k = Convert.ToInt32(cust.Id_Cus);
        dc.customers.Add(cust);
        dc.SaveChanges();

        cust = (from n in dc.customers
                        where n.Id_Cus == k
                        select n).Include(c => c.customerpreference).ToList().First();
}

Возможно, проблема в

cust = (from n in dc.customers
                        where n.Id_Cus == k
                        select n).Include(c => c.customerpreference)
           .ToList().First();

Нет ошибок с ключами и свойствами навигации, и не может быть , поскольку я использовал базу данных в первую очередь.

Customer (из EDMX.model)

namespace WcfRestFullService.Model
{
    using System;
    using System.Collections.Generic;

    public partial class customer
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public customer()
        {
            this.dishesrankings = new HashSet<dishesranking>();
            this.orders = new HashSet<order>();
        }

        public int Id_Cus { get; set; }
        public string FirstName_Cus { get; set; }
        public string LastName_Cus { get; set; }
        public int PhoneNum_Cus { get; set; }
        public string Email_Cus { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<dishesranking> dishesrankings { get; set; }
        public virtual customerpreference customerpreference { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<order> orders { get; set; }
    }
}

CustomerPrefernce (2-я таблица) (из EDMX.model)

namespace WcfRestFullService.Model
{
    using System;
    using System.Collections.Generic;

    public partial class customerpreference
    {
        public int Id_Cus { get; set; }
        public int Id_Res { get; set; }
        public string Name_Dis { get; set; }
        public int Id_Type { get; set; }

        public virtual customer customer { get; set; }
        public virtual order order { get; set; }
        public virtual type_dishes type_dishes { get; set; }
    }
}

EDMX

namespace WcfRestFullService.Model
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class MySQLEntities : DbContext
    {
        public MySQLEntities()
            : base("name=MySQLEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<customer> customers { get; set; }
        public virtual DbSet<customerpreference> customerpreferences { get; set; }
        public virtual DbSet<dish> dishes { get; set; }
        public virtual DbSet<dishesranking> dishesrankings { get; set; }
        public virtual DbSet<ingridient> ingridients { get; set; }
        public virtual DbSet<order> orders { get; set; }
        public virtual DbSet<restaraunt> restaraunts { get; set; }
        public virtual DbSet<type_dishes> type_dishes { get; set; }
    }
}

EDMX / XML

        <EntityType Name="customer">
          <Key>
            <PropertyRef Name="Id_Cus" />
          </Key>
          <Property Name="Id_Cus" Type="int" Nullable="false" />
          <Property Name="FirstName_Cus" Type="varchar" MaxLength="45" Nullable="false" />
          <Property Name="LastName_Cus" Type="varchar" MaxLength="75" Nullable="false" />
          <Property Name="PhoneNum_Cus" Type="int" Nullable="false" />
          <Property Name="Email_Cus" Type="varchar" MaxLength="200" Nullable="false" />
        </EntityType>
        <EntityType Name="customerpreferences">
          <Key>
            <PropertyRef Name="Id_Cus" />
          </Key>
          <Property Name="Id_Cus" Type="int" Nullable="false" />
          <Property Name="Id_Res" Type="int" Nullable="false" />
          <Property Name="Name_Dis" Type="varchar" MaxLength="100" Nullable="false" />
          <Property Name="Id_Type" Type="int" Nullable="false" />
        </EntityType>
        <EntityType Name="dishes">
          <Key>
            <PropertyRef Name="Id_Dis" />
          </Key>
          <Property Name="Id_Dis" Type="int" Nullable="false" />
          <Property Name="Name_Dis" Type="varchar" MaxLength="100" Nullable="false" />
          <Property Name="CookingTime_Dis" Type="int" Nullable="false" />
          <Property Name="Gram" Type="int" Nullable="false" />
          <Property Name="Id_Res" Type="int" Nullable="false" />
          <Property Name="Number_Ord" Type="int" Nullable="false" />
        </EntityType>
        <EntityType Name="dishesranking">
          <Key>
            <PropertyRef Name="Id_Cus" />
            <PropertyRef Name="Id_Dis" />
          </Key>
          <Property Name="Id_Cus" Type="int" Nullable="false" />
          <Property Name="Id_Dis" Type="int" Nullable="false" />
          <Property Name="Rating" Type="int" Nullable="false" />
        </EntityType>
        <EntityType Name="ingridients">
          <Key>
            <PropertyRef Name="Id_Ing" />
          </Key>
          <Property Name="Id_Ing" Type="int" Nullable="false" />
          <Property Name="Name_Ing" Type="varchar" MaxLength="100" Nullable="false" />
          <Property Name="Name_Dis" Type="varchar" MaxLength="100" Nullable="false" />
          <Property Name="Id_Dis" Type="int" Nullable="false" />
        </EntityType>
        <EntityType Name="order">
          <Key>
            <PropertyRef Name="Number_Ord" />
          </Key>
          <Property Name="Number_Ord" Type="int" Nullable="false" />
          <Property Name="Name_Dis" Type="varchar" MaxLength="100" Nullable="false" />
          <Property Name="Id_Cus" Type="int" Nullable="false" />
          <Property Name="Id_Res" Type="int" Nullable="false" />
          <Property Name="Order_Time" Type="timestamp" Precision="6" />
        </EntityType>
        <EntityType Name="restaraunt">
          <Key>
            <PropertyRef Name="Id_Res" />
          </Key>
          <Property Name="Id_Res" Type="int" Nullable="false" />
          <Property Name="Name_Res" Type="varchar" MaxLength="100" Nullable="false" />
          <Property Name="Phone_Res" Type="int" Nullable="false" />
          <Property Name="Dishes_Res" Type="varchar" MaxLength="100" Nullable="false" />
          <Property Name="Adress_Res" Type="varchar" MaxLength="200" Nullable="false" />
          <Property Name="Email_Res" Type="varchar" MaxLength="200" Nullable="false" />
          <Property Name="WebSite_Res" Type="varchar" MaxLength="300" Nullable="false" />
          <Property Name="Rating_Res" Type="int" Nullable="false" />
        </EntityType>
        <EntityType Name="type_dishes">
          <Key>
            <PropertyRef Name="Id_Type" />
          </Key>
          <Property Name="Id_Type" Type="int" Nullable="false" />
          <Property Name="Name_Type" Type="varchar" MaxLength="100" Nullable="false" />
          <Property Name="Id_Dis" Type="int" Nullable="false" />
        </EntityType>
        <Association Name="fk_Customer_has_Dishes_Customer1">
          <End Role="customer" Type="Self.customer" Multiplicity="1" />
          <End Role="dishesranking" Type="Self.dishesranking" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="customer">
              <PropertyRef Name="Id_Cus" />
            </Principal>
            <Dependent Role="dishesranking">
              <PropertyRef Name="Id_Cus" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_Customer_has_Dishes_Dishes1">
          <End Role="dishes" Type="Self.dishes" Multiplicity="1" />
          <End Role="dishesranking" Type="Self.dishesranking" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="dishes">
              <PropertyRef Name="Id_Dis" />
            </Principal>
            <Dependent Role="dishesranking">
              <PropertyRef Name="Id_Dis" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_CustomerPreferences_Customer1">
          <End Role="customer" Type="Self.customer" Multiplicity="1" />
          <End Role="customerpreferences" Type="Self.customerpreferences" Multiplicity="0..1" />
          <ReferentialConstraint>
            <Principal Role="customer">
              <PropertyRef Name="Id_Cus" />
            </Principal>
            <Dependent Role="customerpreferences">
              <PropertyRef Name="Id_Cus" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_CustomerPreferences_Order1">
          <End Role="order" Type="Self.order" Multiplicity="1" />
          <End Role="customerpreferences" Type="Self.customerpreferences" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="order">
              <PropertyRef Name="Number_Ord" />
            </Principal>
            <Dependent Role="customerpreferences">
              <PropertyRef Name="Id_Res" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_CustomerPreferences_Type_Dishes1">
          <End Role="type_dishes" Type="Self.type_dishes" Multiplicity="1" />
          <End Role="customerpreferences" Type="Self.customerpreferences" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="type_dishes">
              <PropertyRef Name="Id_Type" />
            </Principal>
            <Dependent Role="customerpreferences">
              <PropertyRef Name="Id_Type" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_Dishes_Order1">
          <End Role="order" Type="Self.order" Multiplicity="1" />
          <End Role="dishes" Type="Self.dishes" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="order">
              <PropertyRef Name="Number_Ord" />
            </Principal>
            <Dependent Role="dishes">
              <PropertyRef Name="Number_Ord" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_Dishes_Restaraunt1">
          <End Role="restaraunt" Type="Self.restaraunt" Multiplicity="1" />
          <End Role="dishes" Type="Self.dishes" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="restaraunt">
              <PropertyRef Name="Id_Res" />
            </Principal>
            <Dependent Role="dishes">
              <PropertyRef Name="Id_Res" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_Ingridients_Dishes1">
          <End Role="dishes" Type="Self.dishes" Multiplicity="1" />
          <End Role="ingridients" Type="Self.ingridients" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="dishes">
              <PropertyRef Name="Id_Dis" />
            </Principal>
            <Dependent Role="ingridients">
              <PropertyRef Name="Id_Dis" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_Order_Customer">
          <End Role="customer" Type="Self.customer" Multiplicity="1" />
          <End Role="order" Type="Self.order" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="customer">
              <PropertyRef Name="Id_Cus" />
            </Principal>
            <Dependent Role="order">
              <PropertyRef Name="Id_Cus" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_Order_Restaraunt1">
          <End Role="restaraunt" Type="Self.restaraunt" Multiplicity="1" />
          <End Role="order" Type="Self.order" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="restaraunt">
              <PropertyRef Name="Id_Res" />
            </Principal>
            <Dependent Role="order">
              <PropertyRef Name="Id_Res" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_Type_Dishes_Dishes1">
          <End Role="dishes" Type="Self.dishes" Multiplicity="1" />
          <End Role="type_dishes" Type="Self.type_dishes" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="dishes">
              <PropertyRef Name="Id_Dis" />
            </Principal>
            <Dependent Role="type_dishes">
              <PropertyRef Name="Id_Dis" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <EntityContainer Name="ModelStoreContainer">
          <EntitySet Name="customer" EntityType="Self.customer" Schema="chik-chak" store:Type="Tables" />
          <EntitySet Name="customerpreferences" EntityType="Self.customerpreferences" Schema="chik-chak" store:Type="Tables" />
          <EntitySet Name="dishes" EntityType="Self.dishes" Schema="chik-chak" store:Type="Tables" />
          <EntitySet Name="dishesranking" EntityType="Self.dishesranking" Schema="chik-chak" store:Type="Tables" />
          <EntitySet Name="ingridients" EntityType="Self.ingridients" Schema="chik-chak" store:Type="Tables" />
          <EntitySet Name="order" EntityType="Self.order" Schema="chik-chak" store:Type="Tables" />
          <EntitySet Name="restaraunt" EntityType="Self.restaraunt" Schema="chik-chak" store:Type="Tables" />
          <EntitySet Name="type_dishes" EntityType="Self.type_dishes" Schema="chik-chak" store:Type="Tables" />
          <AssociationSet Name="fk_Customer_has_Dishes_Customer1" Association="Self.fk_Customer_has_Dishes_Customer1">
            <End Role="customer" EntitySet="customer" />
            <End Role="dishesranking" EntitySet="dishesranking" />
          </AssociationSet>
          <AssociationSet Name="fk_Customer_has_Dishes_Dishes1" Association="Self.fk_Customer_has_Dishes_Dishes1">
            <End Role="dishes" EntitySet="dishes" />
            <End Role="dishesranking" EntitySet="dishesranking" />
          </AssociationSet>
          <AssociationSet Name="fk_CustomerPreferences_Customer1" Association="Self.fk_CustomerPreferences_Customer1">
            <End Role="customer" EntitySet="customer" />
            <End Role="customerpreferences" EntitySet="customerpreferences" />
          </AssociationSet>
          <AssociationSet Name="fk_CustomerPreferences_Order1" Association="Self.fk_CustomerPreferences_Order1">
            <End Role="order" EntitySet="order" />
            <End Role="customerpreferences" EntitySet="customerpreferences" />
          </AssociationSet>
          <AssociationSet Name="fk_CustomerPreferences_Type_Dishes1" Association="Self.fk_CustomerPreferences_Type_Dishes1">
            <End Role="type_dishes" EntitySet="type_dishes" />
            <End Role="customerpreferences" EntitySet="customerpreferences" />
          </AssociationSet>
          <AssociationSet Name="fk_Dishes_Order1" Association="Self.fk_Dishes_Order1">
            <End Role="order" EntitySet="order" />
            <End Role="dishes" EntitySet="dishes" />
          </AssociationSet>
          <AssociationSet Name="fk_Dishes_Restaraunt1" Association="Self.fk_Dishes_Restaraunt1">
            <End Role="restaraunt" EntitySet="restaraunt" />
            <End Role="dishes" EntitySet="dishes" />
          </AssociationSet>
          <AssociationSet Name="fk_Ingridients_Dishes1" Association="Self.fk_Ingridients_Dishes1">
            <End Role="dishes" EntitySet="dishes" />
            <End Role="ingridients" EntitySet="ingridients" />
          </AssociationSet>
          <AssociationSet Name="fk_Order_Customer" Association="Self.fk_Order_Customer">
            <End Role="customer" EntitySet="customer" />
            <End Role="order" EntitySet="order" />
          </AssociationSet>
          <AssociationSet Name="fk_Order_Restaraunt1" Association="Self.fk_Order_Restaraunt1">
            <End Role="restaraunt" EntitySet="restaraunt" />
            <End Role="order" EntitySet="order" />
          </AssociationSet>
          <AssociationSet Name="fk_Type_Dishes_Dishes1" Association="Self.fk_Type_Dishes_Dishes1">
            <End Role="dishes" EntitySet="dishes" />
            <End Role="type_dishes" EntitySet="type_dishes" />
          </AssociationSet>
        </EntityContainer>
      </Schema></edmx:StorageModels>
    <!-- CSDL content -->
    <edmx:ConceptualModels>
      <Schema Namespace="Model" Alias="Self" annotation:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns:customannotation="http://schemas.microsoft.com/ado/2013/11/edm/customannotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
        <EntityType Name="customer">
          <Key>
            <PropertyRef Name="Id_Cus" />
          </Key>
          <Property Name="Id_Cus" Type="Int32" Nullable="false" />
          <Property Name="FirstName_Cus" Type="String" MaxLength="45" FixedLength="false" Unicode="false" Nullable="false" />
          <Property Name="LastName_Cus" Type="String" MaxLength="75" FixedLength="false" Unicode="false" Nullable="false" />
          <Property Name="PhoneNum_Cus" Type="Int32" Nullable="false" />
          <Property Name="Email_Cus" Type="String" MaxLength="200" FixedLength="false" Unicode="false" Nullable="false" />
          <NavigationProperty Name="dishesrankings" Relationship="Self.fk_Customer_has_Dishes_Customer1" FromRole="customer" ToRole="dishesranking" />
          <NavigationProperty Name="customerpreference" Relationship="Self.fk_CustomerPreferences_Customer1" FromRole="customer" ToRole="customerpreferences" />
          <NavigationProperty Name="orders" Relationship="Self.fk_Order_Customer" FromRole="customer" ToRole="order" />
        </EntityType>
        <EntityType Name="customerpreference">
          <Key>
            <PropertyRef Name="Id_Cus" />
          </Key>
          <Property Name="Id_Cus" Type="Int32" Nullable="false" />
          <Property Name="Id_Res" Type="Int32" Nullable="false" />
          <Property Name="Name_Dis" Type="String" MaxLength="100" FixedLength="false" Unicode="false" Nullable="false" />
          <Property Name="Id_Type" Type="Int32" Nullable="false" />
          <NavigationProperty Name="customer" Relationship="Self.fk_CustomerPreferences_Customer1" FromRole="customerpreferences" ToRole="customer" />
          <NavigationProperty Name="order" Relationship="Self.fk_CustomerPreferences_Order1" FromRole="customerpreferences" ToRole="order" />
          <NavigationProperty Name="type_dishes" Relationship="Self.fk_CustomerPreferences_Type_Dishes1" FromRole="customerpreferences" ToRole="type_dishes" />
        </EntityType>
        <EntityType Name="dish">
          <Key>
            <PropertyRef Name="Id_Dis" />
          </Key>
          <Property Name="Id_Dis" Type="Int32" Nullable="false" />
          <Property Name="Name_Dis" Type="String" MaxLength="100" FixedLength="false" Unicode="false" Nullable="false" />
          <Property Name="CookingTime_Dis" Type="Int32" Nullable="false" />
          <Property Name="Gram" Type="Int32" Nullable="false" />
          <Property Name="Id_Res" Type="Int32" Nullable="false" />
          <Property Name="Number_Ord" Type="Int32" Nullable="false" />
          <NavigationProperty Name="dishesrankings" Relationship="Self.fk_Customer_has_Dishes_Dishes1" FromRole="dishes" ToRole="dishesranking" />
          <NavigationProperty Name="order" Relationship="Self.fk_Dishes_Order1" FromRole="dishes" ToRole="order" />
          <NavigationProperty Name="restaraunt" Relationship="Self.fk_Dishes_Restaraunt1" FromRole="dishes" ToRole="restaraunt" />
          <NavigationProperty Name="ingridients" Relationship="Self.fk_Ingridients_Dishes1" FromRole="dishes" ToRole="ingridients" />
          <NavigationProperty Name="type_dishes" Relationship="Self.fk_Type_Dishes_Dishes1" FromRole="dishes" ToRole="type_dishes" />
        </EntityType>
        <EntityType Name="dishesranking">
          <Key>
            <PropertyRef Name="Id_Cus" />
            <PropertyRef Name="Id_Dis" />
          </Key>
          <Property Name="Id_Cus" Type="Int32" Nullable="false" />
          <Property Name="Id_Dis" Type="Int32" Nullable="false" />
          <Property Name="Rating" Type="Int32" Nullable="false" />
          <NavigationProperty Name="customer" Relationship="Self.fk_Customer_has_Dishes_Customer1" FromRole="dishesranking" ToRole="customer" />
          <NavigationProperty Name="dish" Relationship="Self.fk_Customer_has_Dishes_Dishes1" FromRole="dishesranking" ToRole="dishes" />
        </EntityType>
        <EntityType Name="ingridient">
          <Key>
            <PropertyRef Name="Id_Ing" />
          </Key>
          <Property Name="Id_Ing" Type="Int32" Nullable="false" />
          <Property Name="Name_Ing" Type="String" MaxLength="100" FixedLength="false" Unicode="false" Nullable="false" />
          <Property Name="Name_Dis" Type="String" MaxLength="100" FixedLength="false" Unicode="false" Nullable="false" />
          <Property Name="Id_Dis" Type="Int32" Nullable="false" />
          <NavigationProperty Name="dish" Relationship="Self.fk_Ingridients_Dishes1" FromRole="ingridients" ToRole="dishes" />
        </EntityType>
        <EntityType Name="order">
          <Key>

        </EntityType>
          <NavigationProperty Name="orders" Relationship="Self.fk_Order_Restaraunt1" FromRole="restaraunt" ToRole="order" />
        Relationship="Self.fk_Type_Dishes_Dishes1" FromRole="type_dishes" ToRole="dishes" />
        </EntityType>
        <Association Name="fk_Customer_has_Dishes_Customer1">
          <End Role="customer" Type="Self.customer" Multiplicity="1" />
          <End Role="dishesranking" Type="Self.dishesranking" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="customer">
              <PropertyRef Name="Id_Cus" />
            </Principal>
            <Dependent Role="dishesranking">
              <PropertyRef Name="Id_Cus" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_CustomerPreferences_Customer1">
          <End Role="customer" Type="Self.customer" Multiplicity="1" />
          <End Role="customerpreferences" Type="Self.customerpreference" Multiplicity="0..1" />
          <ReferentialConstraint>
            <Principal Role="customer">
              <PropertyRef Name="Id_Cus" />
            </Principal>
            <Dependent Role="customerpreferences">
              <PropertyRef Name="Id_Cus" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_Order_Customer">
          <End Role="customer" Type="Self.customer" Multiplicity="1" />
          <End Role="order" Type="Self.order" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="customer">
              <PropertyRef Name="Id_Cus" />
            </Principal>
            <Dependent Role="order">
              <PropertyRef Name="Id_Cus" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_CustomerPreferences_Order1">
          <End Role="order" Type="Self.order" Multiplicity="1" />
          <End Role="customerpreferences" Type="Self.customerpreference" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="order">
              <PropertyRef Name="Number_Ord" />
            </Principal>
            <Dependent Role="customerpreferences">
              <PropertyRef Name="Id_Res" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
            <Dependent Role="customerpreferences">
              <PropertyRef Name="Id_Type" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="fk_Dishes_Restaraunt1">
          Association="Self.fk_Customer_has_Dishes_Customer1">
            <End Role="customer" EntitySet="customers" />
            <End Role="dishesranking" EntitySet="dishesrankings" />
          </AssociationSet>
          <AssociationSet Name="fk_CustomerPreferences_Customer1" Association="Self.fk_CustomerPreferences_Customer1">
            <End Role="customer" EntitySet="customers" />
            <End Role="customerpreferences" EntitySet="customerpreferences" />
          </AssociationSet>
          <AssociationSet Name="fk_Order_Customer" Association="Self.fk_Order_Customer">
            <End Role="customer" EntitySet="customers" />
            <End Role="order" EntitySet="orders" />
          </AssociationSet>
          <AssociationSet Name="fk_CustomerPreferences_Order1" Association="Self.fk_CustomerPreferences_Order1">
            <End Role="order" EntitySet="orders" />
            <End Role="customerpreferences" EntitySet="customerpreferences" />
          </AssociationSet>
          </AssociationSet>
          </AssociationSet>
        </EntityContainer>
      </Schema>
    </edmx:ConceptualModels>
    <!-- C-S mapping content -->
    <edmx:Mappings>
      <Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs">
        <EntityContainerMapping StorageEntityContainer="ModelStoreContainer" CdmEntityContainer="MySQLEntities">
          <EntitySetMapping Name="customers">
            <EntityTypeMapping TypeName="Model.customer">
              <MappingFragment StoreEntitySet="customer">
                <ScalarProperty Name="Id_Cus" ColumnName="Id_Cus" />
                <ScalarProperty Name="FirstName_Cus" ColumnName="FirstName_Cus" />
                <ScalarProperty Name="LastName_Cus" ColumnName="LastName_Cus" />
                <ScalarProperty Name="PhoneNum_Cus" ColumnName="PhoneNum_Cus" />
                <ScalarProperty Name="Email_Cus" ColumnName="Email_Cus" />
              </MappingFragment>
            </EntityTypeMapping>
          </EntitySetMapping>
          <EntitySetMapping Name="customerpreferences">
            <EntityTypeMapping TypeName="Model.customerpreference">
              <MappingFragment StoreEntitySet="customerpreferences">
                <ScalarProperty Name="Id_Cus" ColumnName="Id_Cus" />
                <ScalarProperty Name="Id_Res" ColumnName="Id_Res" />
                <ScalarProperty Name="Name_Dis" ColumnName="Name_Dis" />
                <ScalarProperty Name="Id_Type" ColumnName="Id_Type" />
              </MappingFragment>
            </EntityTypeMapping>
          </EntitySetMapping>

введите описание изображения здесь

введите описание изображения здесь

введите описание изображения здесь

1 Ответ

0 голосов
/ 13 апреля 2020

Теперь я думаю, что у нас есть вся информация, чтобы обозначить проблемы, с которыми вы столкнулись Суть в том, что ограничения внешнего ключа (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 между вашими таблицами, чтобы я мог привести небольшой пример. Однако, чтобы вставить данные в базу данных, вам нужно сделать это в следующем порядке:

  1. Вставить restaraunt (rest1)
  2. Вставить customer (cust1)
  3. Вставка order (ord1), где:
    • ord1.Id_Cus = cust1.Id_Cus
    • ord1.Id_Res = rest1.Id_Res
  4. Вставка dishes (dish1), где:
    • dish1.Number_Ord = ord1.Number_Ord
    • dish1.Id_Res = rest1.Id_Res
  5. Вставка type_dishes (typDish1 ), где:
    • typDish1.Id_Dis = dish1.Id_Dis
  6. Вставка 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
}
-```
...