Связь между таблицами в WCF - PullRequest
0 голосов
/ 23 апреля 2020

У меня следующий вопрос. Я создал базу данных в MySQL, затем использовал первый подход к базе данных и импортировал базу данных в VS. Ниже приведены две таблицы, с которыми я работаю. 1-я таблица

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

    public partial class customer
    {
        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; }

        public virtual ICollection<dishesranking> dishesrankings { get; set; }
        public virtual customerpreference customerpreference { get; set; }
        public virtual ICollection<order> orders { get; set; }
    }
}

2-я таблица

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; }
    }
}

далее, я работаю с этими таблицами в службе WCF, поэтому реализация каждой таблицы выполняется в своем собственном классе.

1-я таблица логи c

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using MySql.Data;
using System.Data.Entity;

using WcfRestFullService.Model;

namespace WcfRestFullService
{
    public class CustomerSevice : ICustomerSevice
    {
        MySQLEntities dc;
        public CustomerSevice()
        {
            dc = new MySQLEntities();
        }

        public List<customer> GetAllCustomer()
        {
            var query = (from a in dc.customers
                         select a).Distinct().Include(c => c.customerpreference);

            List<customer> CustomersList = new List<customer>();

            query.ToList().ForEach(x =>
            {
                CustomersList.Add(new customer
                {
                    Id_Cus = x.Id_Cus,
                    FirstName_Cus = x.FirstName_Cus,
                    LastName_Cus = x.LastName_Cus,
                    PhoneNum_Cus = x.PhoneNum_Cus,
                    Email_Cus = x.Email_Cus,
                });
            });
            return CustomersList;
        }

        public customer CustomerDetails(string Id_Cus)
        {
            customer Cust = new customer();
            try
            {
                var query = (from a in dc.customers
                             where a.Id_Cus.Equals(Id_Cus)
                             select a).Distinct().FirstOrDefault();
                Cust.Id_Cus = query.Id_Cus;
                Cust.FirstName_Cus = query.FirstName_Cus;
                Cust.LastName_Cus = query.LastName_Cus;
                Cust.PhoneNum_Cus = query.PhoneNum_Cus;
                Cust.Email_Cus = query.Email_Cus;
            }
            catch (Exception ex)
            {
                throw new FaultException<string>(ex.Message);
            }
            return Cust;
        }

        // DELETE

        public void DeleteCustomer(string Id_Cus)
        {
            //MySQLEntities Cust = new MySQLEntities(); //check the file Model.edmx->ModelContext.tt->MySQLEntitys

            int k = Convert.ToInt32(Id_Cus);
            customer cur = (from n in dc.customers
                            where n.Id_Cus == k
                            select n).Include(c => c.customerpreference).Include(c => c.orders).Include(c => c.dishesrankings).ToList().First();


            dc.Configuration.ValidateOnSaveEnabled = false;
            dc.customers.Remove(cur);
            dc.SaveChanges();
        }

        //Insert/POST

        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;
                //}
                Dictionary<string, int> dict = dc.customers.GroupBy(x => x.Email_Cus, y => y.Id_Cus)
                                                                 .ToDictionary(x => x.Key, y => y.FirstOrDefault());

                dc.customers.Add(cust);

            //string p = "Vasa";
            customerpreference Cus_Pref = new customerpreference()
            {
                Id_Cus = customerDataContract.Id_Cus,
                Id_Res = 1, // some value
                Name_Dis = "lion", // some value
                Id_Type = 1 // some value
            };
                dc.customerpreferences.Add(Cus_Pref);
                dc.SaveChanges();
                int k = Convert.ToInt32(cust.Id_Cus);
                customer custFromDb = (from n in dc.customers
                                       where n.Id_Cus == k
                                       select n).Include(c => c.customerpreference).Include(c=>c.orders).Include(c=>c.dishesrankings).First();
            }

        }

        //Update/PUT
        public void UpdateCustomer(customer customerDataContract)
        {
            //using (CustomerDataContract Cust = new CustomerDataContract())
            //using (MySQLEntities Cust = new MySQLEntities()) 

                int k = Convert.ToInt32(customerDataContract.Id_Cus);
                customer cust = dc.customers.Where(n => n.Id_Cus == k).FirstOrDefault();

                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;

                dc.SaveChanges();

        }
    }
}

2-я таблица логи c

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using MySql.Data.MySqlClient;

using WcfRestFullService.Model;

namespace WcfRestFullService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CustomerPreferences" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select CustomerPreferences.svc or CustomerPreferences.svc.cs at the Solution Explorer and start debugging.
    public class CustomerPreferences : ICustomerPreferences//, IDisposable
    {


         MySQLEntities dc;                     //LIKE This
        string connStr = "server=localhost;user=root;port=3306;database=chik-chak;password=l10ksfnq5h2c";
         public CustomerPreferences() 
         {
             dc = new MySQLEntities(); //Perhaps the problem is that I'm trying to create a new database, so the data is not imported from the first table, do I need these lines of code ??
            //MySqlConnection conn = new MySqlConnection(connStr);
            //conn.Open();
         }

        public customerpreference CustomerDetails(string Id_Cus)
        {

                customerpreference Cust = new customerpreference();
            try
            {
                var query = (from a in dc.customerpreferences
                             where a.Id_Cus.Equals(Id_Cus)
                             select a).Distinct().FirstOrDefault();
                Cust.Id_Cus = query.Id_Cus;
                Cust.Id_Res = query.Id_Res;
                Cust.Name_Dis = query.Name_Dis;
                Cust.Id_Type = query.Id_Type;
            }
            catch (Exception ex)
            {
                throw new FaultException<string>(ex.Message);
            }
            return Cust;
        }

        public void DeleteCustomerPreference(string Id_Cus)
        {
            int k = Convert.ToInt32(Id_Cus);
            customerpreference cur = (from n in dc.customerpreferences
                            where n.Id_Cus == k
                            select n).ToList().First();

            dc.Configuration.ValidateOnSaveEnabled = false;
            dc.customerpreferences.Remove(cur);
            dc.SaveChanges();
        }

        public List<customerpreference> GetAllCustomerPreferences()
        {
            MySqlConnection conn = new MySqlConnection(connStr);
            conn.Open();
            //string quer = "SELECT Id_Cus, Name, Description, Price FROM tb_Products";

            var query = (from a in dc.customerpreferences 
                         select a).Distinct();
            string k = query.ToString();
            MySqlCommand command = new MySqlCommand(k, conn);

            List<customerpreference> CustomersList = new List<customerpreference>();

            query.ToList().ForEach(x =>
            {
                CustomersList.Add(new customerpreference
                {
                    Id_Cus = x.Id_Cus,
                    Id_Res = x.Id_Res,
                    Name_Dis = x.Name_Dis,
                    Id_Type = x.Id_Type,
                });
            });
            //dc.Connection = conn;
            //dc.CommandText = query.ToString();
            //conn.Close();
            return CustomersList;
        }

        public void InsertCustomerPreference(customerpreference customerDataContractpreference)
        {
            customerpreference cust = new customerpreference();

                cust.Id_Cus = customerDataContractpreference.Id_Cus;
                cust.Id_Res = customerDataContractpreference.Id_Res;
                cust.Id_Type = customerDataContractpreference.Id_Type;
                cust.Name_Dis = customerDataContractpreference.Name_Dis;


            /*MySqlConnection conn = new MySqlConnection(connStr);
            conn.Open();
            string query = "INSERT INTO tb_customerpreferences VALUES (@Id_Cus, @Id_Res, @Name_Dis,@Id_Type);";
            MySqlCommand command = new MySqlCommand(query, conn);
            command.Parameters.Add(cust.Id_Cus = customerDataContractpreference.Id_Cus);
            command.Parameters.Add(cust.Id_Res = customerDataContractpreference.Id_Res);
            command.Parameters.Add(cust.Name_Dis = customerDataContractpreference.Name_Dis);
            command.Parameters.Add(cust.Id_Type = customerDataContractpreference.Id_Type);*/

            dc.customerpreferences.Add(cust);
            dc.SaveChanges();
        }

        public void UpdateCustomerPreference(customerpreference customerDataContractpreference)
        {
            int k = customerDataContractpreference.Id_Cus;
            customerpreference cust = dc.customerpreferences.Where(n => n.Id_Cus == k).FirstOrDefault();

            cust.Id_Cus = customerDataContractpreference.Id_Cus;
            cust.Id_Res = customerDataContractpreference.Id_Res;
            cust.Name_Dis = customerDataContractpreference.Name_Dis;
            cust.Id_Type = customerDataContractpreference.Id_Type;

            dc.SaveChanges();
        }
    }
}

В этих методах все работает нормально (см. Первое и второе изображение)

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

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

, поэтому оба метода работают правильно, однако существует проблема. если вы снова посмотрите на первое фото, вы увидите, что таблица customerpreferences является нулевой, хотя на самом деле она не является, в свою очередь, таблица customerpreferences ссылается на следующие таблицы, а также показывает, что они нулевые, что не соответствует реальность. Я не знаю, в чем может быть проблема, если EF правильно установил все ключи, но по какой-то причине данные не подключены. Обратите внимание только на два метода: INSERT, DELETE, поскольку только эти методы работают со связанными данными. На мой взгляд, ошибка может заключаться в следующем: в первой таблице перед всеми методами я создаю

MySQLEntities dc;
        public CustomerSevice()
        {
            dc = new MySQLEntities();
        }

Однако во второй и последующих таблицах я воссоздаю базу данных.

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

MySQLEntities dc;                     //LIKE This
        string connStr = "server=localhost;user=root;port=3306;database=chik-chak;password=l10ksfnq5h2c";
// code
//insert method
public void InsertCustomerPreference(customerpreference customerDataContractpreference)
        {
            customerpreference cust = new customerpreference();
            /*MySqlConnection conn = new MySqlConnection(connStr);
            conn.Open();
            string query = "INSERT INTO tb_customerpreferences VALUES (@Id_Cus, @Id_Res, @Name_Dis,@Id_Type);";
            MySqlCommand command = new MySqlCommand(query, conn);
            command.Parameters.Add(cust.Id_Cus = customerDataContractpreference.Id_Cus);
            command.Parameters.Add(cust.Id_Res = customerDataContractpreference.Id_Res);
            command.Parameters.Add(cust.Name_Dis = customerDataContractpreference.Name_Dis);
            command.Parameters.Add(cust.Id_Type = customerDataContractpreference.Id_Type);*/

            dc.customerpreferences.Add(cust);
            dc.SaveChanges();
        }

Я признаю, что проблема может быть не в соединении, но что я указал что-то не так, скажите, пожалуйста, в чем может быть проблема? Спасибо за внимание и за любые советы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...