[英]Add SQL SELECT query result to List
我是C#的新手,對如何建立與MySql數據庫的連接不是很熟悉。
我確實有一個名為packages的表,其中包含我為其創建的模型:
namespace CService.Models
{
public class Package
{
public int id { get; set; }
public String name { get; set; }
public String description { get; set; }
public Boolean tracking { get; set; }
public int senderCityId { get; set; }
public int destinationCityId { get; set; }
public int senderId { get; set; }
public int receiverId { get; set; }
public Package(int id, string name, string description, Boolean tracking, int senderCityId,
int destinationCityId, int senderId, int receiverId)
{
this.id = id;
this.name = name;
this.description = description;
this.tracking = tracking;
this.senderCityId = senderCityId;
this.destinationCityId = destinationCityId;
this.senderId = senderId;
this.receiverId = receiverId; }
}
}
我試圖做出一條選擇語句,並將結果分配給本地列表 :
MySqlConnection conn = new MySqlConnection("server = localhost; user id = root; database=assignment_four; password=Mysqlpassword123");
public List<Package> getPackages()
{
List<Package> packages = new List<Package>();
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * from packages";
MySqlDataReader reader = cmd.ExecuteReader();
try
{
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
packages.Add(new Package(
reader.GetInt32(reader.GetOrdinal("id")),
reader.GetString(reader.GetOrdinal("name")),
reader.GetString(reader.GetOrdinal("description")),
reader.GetBoolean(reader.GetOrdinal("tracking")),
reader.GetInt32(reader.GetOrdinal("senderCity_id")),
reader.GetInt32(reader.GetOrdinal("destinationCity_id")),
reader.GetInt32(reader.GetOrdinal("sender_id")),
reader.GetInt32(reader.GetOrdinal("receiver_id"))
));
}
reader.Close();
}
catch (Exception exp)
{
throw;
}
finally
{
conn.Close();
}
return packages;
但是,當我嘗試將其作為WCF服務運行時,出現以下錯誤:
添加服務失敗。 服務元數據可能無法訪問。 確保您的服務正在運行並公開元數據。
在添加上述代碼之前,該服務已經正常工作,因此我認為問題出在我的數據檢索方法中。
首先,錯誤詳細信息主要表明我們應該公開服務元數據以便在客戶端使用服務,但這無法解決我們的問題。
其次,我們應該將OperationContractAttribute添加到操作方法,並將DataContractAttribute添加到自定義復雜類型。
我做了一個演示,希望對您有用。
接口和服務實施
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(RequestFormat =WebMessageFormat.Json,ResponseFormat =WebMessageFormat.Json)]
List<Product> GetProducts(); }
[DataContract]
public class Product
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Price { get; set; }
public Product(int id, string name, int price)
{
this.ID = id;
this.Name = name;
this.Price = price;
} }
public class Service1 : IService1
{
public List<Product> GetProducts()
{
List<Product> products = new List<Product>();
SqlConnection connection = new SqlConnection(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DataStore;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
SqlCommand command = new SqlCommand("select * from Products", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
products.Add(new Product(reader.GetInt32((reader.GetOrdinal("Id"))), reader.GetString(reader.GetOrdinal("Name")), reader.GetInt32(reader.GetOrdinal("Price"))));
}
reader.Close();
connection.Close();
return products;
}
}
web.config中
<system.serviceModel>
<services>
<service name="WcfService1.Service1">
<endpoint address="" binding="webHttpBinding" contract="WcfService1.IService1" behaviorConfiguration="rest"></endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="rest">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" httpGetUrl="mex"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
結果。 此外,必須注意的是,如果要在IIS中查詢localdb數據庫(vs2017內置數據庫),則應在承載wcf服務的IIS應用程序池中配置以下內容。
loadUserProfile="true" setProfileEnvironment="true"
請隨時告訴我是否有什么我可以幫助的。
首先,我建議您將Entity Framework用作ORM 。
這些是您必須對代碼進行的更改。 基本上,您嘗試在打開連接之前執行讀取器:
public List<Package> getPackages()
{
var conn = new MySqlConnection("server = localhost; user id = root; database=assignment_four; password=Mysqlpassword123");
var packages = new List<Package>();
try
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * from packages";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
packages.Add(new Package(
reader.GetInt32(reader.GetOrdinal("id")),
reader.GetString(reader.GetOrdinal("name")),
reader.GetString(reader.GetOrdinal("description")),
reader.GetBoolean(reader.GetOrdinal("tracking")),
reader.GetInt32(reader.GetOrdinal("senderCity_id")),
reader.GetInt32(reader.GetOrdinal("destinationCity_id")),
reader.GetInt32(reader.GetOrdinal("sender_id")),
reader.GetInt32(reader.GetOrdinal("receiver_id"))
));
}
reader.Close();
}
}
}
catch (Exception exp)
{
throw;
}
finally
{
conn.Close();
}
return packages;
}
代碼的一些見解:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.