Я создаю сервер на сервере WCF. У меня есть база данных, в которой есть несколько таблиц. Для каждой из таблиц необходимо создать службу WCF. У службы WCF есть два файла: интерфейс, в котором я реализую свою архитектуру REST, и микроволновый файл, в котором я реализую методы, которые я вызываю для этого интерфейса.
При работе с базой данных сначала использовалась база данных EF. Это означает, что данные были импортированы из MySQL самой платформой и автоматически установленными соединениями.
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; }
}
}
3-я таблица (импорт из БД)
namespace WcfRestFullService.Model
{
using System;
using System.Collections.Generic;
public partial class order
{
public order()
{
this.customerpreferences = new HashSet<customerpreference>();
this.dishes = new HashSet<dish>();
}
public int Number_Ord { get; set; }
public string Name_Dis { get; set; }
public int Id_Cus { get; set; }
public int Id_Res { get; set; }
public Nullable<System.DateTime> Order_Time { get; set; }
public virtual customer customer { get; set; }
public virtual ICollection<customerpreference> customerpreferences { get; set; }
public virtual ICollection<dish> dishes { get; set; }
public virtual restaraunt restaraunt { get; set; }
}
}
et c ..
WCF ///
Интерфейс 1-й таблицы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using WcfRestFullService.Model;
namespace WcfRestFullService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICustomerSevice" in both code and config file together.
[ServiceContract]
public interface ICustomerSevice
{
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetAllCustomer/")]//ok
List<customer> GetAllCustomer();
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/CustomerDetails/{Id_Cus}")]
customer CustomerDetails(String Id_Cus);
[OperationContract]
[WebInvoke(Method = "DELETE", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
void DeleteCustomer(String Id_Cus);
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
//BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/InsertCustomer/")]//problem
void InsertCustomer(customer customerDataContract);
[OperationContract]
[WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
//BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/UpdateCustomer/")]//problem
void UpdateCustomer(customer customerDataContract);
}
}
Интерфейс 2-й таблицы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using WcfRestFullService.Model;
namespace WcfRestFullService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICustomerPreferences" in both code and config file together.
[ServiceContract]
public interface ICustomerPreferences
{
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetAllCustomerPreferences/")]
List<customerpreference> GetAllCustomerPreferences();
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/CustomerPreferencesDetails/{Id_Cus}")]
customerpreference CustomerDetails(string Id_cus);
[OperationContract]
[WebInvoke(Method = "DELETE", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
void DeleteCustomerPreference(String Id_Cus);
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
//BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/InsertCustomer/")]//problem
void InsertCustomerPreference(customerpreference customerDataContractpreference);
[OperationContract]
[WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
//BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/UpdateCustomer/")]//problem
void UpdateCustomerPreference(customerpreference customerDataContractpreference);
}
}
и т. Д., Все они одинаково зарегистрированы.
SV C файл для 1-й таблицы
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
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CustomerSevice" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select CustomerSevice.svc or CustomerSevice.svc.cs at the Solution Explorer and start debugging.
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();
}
}
}
SV C для 2-го стола
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
{
MySQLEntities dc; //LIKE This
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 ??
}
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 = DBUtils.GetDBConnection();
//conn.Open();
//MySqlCommand dc = new MySqlCommand();
//dc.Connection = conn;
// MySQLEntities dc;
var query = (from a in dc.customerpreferences
select a).Distinct();
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.Name_Dis = customerDataContractpreference.Name_Dis;
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();
}
}
}
et c. Как видите, logi c в интерфейсах и файлах SV C одинаковы. Вопрос в том, что все архитектура и функции работают правильно. Однако проблема заключается в том, что данные записываются в каждую из таблиц отдельно, но вместе они не связаны (хотя свойства навигации и ключи установлены). Таким образом, похоже, что таблицы не связаны друг с другом. Не могли бы вы предложить, как и что следует указывать в файле SV C, чтобы данные автоматически переносились в связанные таблицы.
I думаю, что проблема может быть здесь, поскольку я создаю ее в каждом из файлов SV C, кроме этого, проблема может быть в строке подключения, так что строка подключения записывается в каждом из этих файлов. но я не знаю, как это сделать.
MySQLEntities dc; //LIKE This
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 ??
}
Мне кажется, что при рассмотрении нужно учитывать метод get и delete, потому что update и get просто работают с данными