我正在尝试使用ASP.Net Web API构建一个Web应用程序。但我发现连接数据库非常困难。起初我使用了web.config中的Entity框架连接字符串,它给了我错误
Keyword not supported: 'metadata'
所以我搜索了很长时间并尝试按照几种解决方案的建议实现EntityConnectionStringBuilder。我有一个使用ADO.Net数据模型生成的产品模型。当我尝试访问getallproducts时,我的datareader中没有任何内容。
'Product' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. Near escaped identifier, line 1, column 37.
现在这就是我尝试过的事情
ProductRepository.cs
using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class ProductRepository : IProductRepository
{
//public string cs = System.Configuration.ConfigurationManager.ConnectionStrings["MediaSoftAppEntities"].ConnectionString;
public IEnumerable<Product> GetAll()
{
string providerName = "System.Data.SqlClient";
string serverName = ".";
string databaseName = "MediaSoftApp";
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = @"res://*/Models.Model1.csdl|
res://*/Models.Model1.ssdl|
res://*/Models.Model1.msl";
List<Product> products = new List<Product>();
string sql = String.Format("Select [pid], [pname], [price] FROM [Product]");
using (EntityConnection con = new EntityConnection(entityBuilder.ToString())){
using (EntityCommand cmd = new EntityCommand(sql, con)){
con.Open();
EntityDataReader dr = cmd.ExecuteReader();
while(dr.Read()){
Product product = new Product();
product.pid = dr.GetInt32(0);
product.pname = dr.GetString(1);
product.price = dr.GetInt32(2);
}
}
}
return products.ToArray();
}
}
}
Product.cs
namespace WebApplication1.Models
{
using System;
using System.Collections.Generic;
public partial class Product
{
public int pid { get; set; }
public string pname { get; set; }
public int price { get; set; }
}
}
ProductController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class ProductController : ApiController
{
static readonly IProductRepository repo = new ProductRepository();
public IEnumerable<Product> GetAllProducts()
{
return repo.GetAll();
}
}
}
更新
的Web.config
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<connectionStrings>
<add name="MediaSoftAppEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MediaSoftApp.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>