Обработка сервера базы данных Advantage с помощью Entity Framework в ASP.NET MVP3
Мне нужно обработать Advantage Database Server(ADS Ver.9.1) с помощью Entity Framework в среде ASP.net MVC3.
Я уже потратил почти 2 недели только на это:(но все равно не смог найти ответ.
Чтобы получить правильный совет, я постараюсь показать шаг за шагом, как и что я сделал. поэтому, если вы обнаружите какую-то ошибку, которую я сделал, или вы знаете что-то, что я могу попробовать, пожалуйста, сообщите мне. плз..
Во-первых, я создал таблицу TEST в ADS.
CREATE TABLE TEST (
ID AutoInc,
Name CIChar( 50 )) IN DATABASE;
и определить идентификатор в качестве первичного ключа.
И я попытался получить доступ к этой таблице с помощью консольного приложения.
Используя Visual Studio 2010, создайте новое консольное приложение (C#)
и я набрал вот так,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Advantage.Data.Provider;
namespace Ads_Console_Test
{
class Program
{
static void Main(string[] args)
{
AdsConnection conn = new AdsConnection("Data Source=\\\\10.0.111.4:6262\\20090622\\SHK\\SHK.ADD;ServerType=REMOTE;User ID=AdsSys;Password=XXXXX;");
AdsCommand cmd;
AdsDataReader reader;
int iField;
try
{
// make the connection to the server
conn.Open();
// create a command object
cmd = conn.CreateCommand();
// specify a simple SELECT statement
cmd.CommandText = "select * from TEST";
// execute the statement and create a reader
reader = cmd.ExecuteReader();
// dump the results of the query to the console
while (reader.Read())
{
for (iField = 0; iField < reader.FieldCount; iField++)
Console.Write(reader.GetValue(iField) + " ");
Console.WriteLine();
}
// close the reader (can’t execute other statements
// on this command or connection) until it is closed
reader.Close();
conn.Close();
}
catch (AdsException e)
{
// print the exception message
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
и запустите, затем он успешно подключится к ADS и получит данные.
Как видите, таблица имеет 3 строки.
Сейчас,
Я попытаюсь получить доступ к ADS, используя Entity Framework. (MVC3)
Я создаю новый проект с MVC3 Framework. и выбрал пустой шаблон.
И добавьте Advantage.Data.Provider в справочник.
Затем я изменил Web.Config(корневой) файл, добавив connectionStrings.
<connectionStrings>
<add name="EFAdsContext" connectionString="Data Source=\\10.0.111.4:6262\20090622\SHK\SHK.ADD;ServerType=REMOTE;User ID=adsSys;Password=XXXXX;
TrimTrailingSpaces=True;" providerName="Advantage.Data.Provider" />
</connectionStrings>
И я создал 3 класса в папке Models.
- EFAdsContext.cs
- TestRepository.cs
- TEST.cs
Вот коды,
1. EFAdsContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Ads_test_mvc3.Models
{
public class EFAdsContext : DbContext
{
public DbSet<TEST> TEST { get; set; }
}
}
2. TestRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ads_test_mvc3.Models
{
public class TestRepository
{
private EFAdsContext context = new EFAdsContext();
public IQueryable<TEST> test
{
get { return context.TEST; }
}
}
}
3. TEST.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Ads_test_mvc3.Models
{
public class TEST
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
}
И создайте HomeControllers.cs в папке Controllers.
HomeControllers.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ads_test_mvc3.Models;
namespace Ads_test_mvc3.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
TestRepository tests = new TestRepository();
int cnt = tests.test.Count();
ViewBag.cnt = cnt;
return View();
}
}
}
И наконец добавить представление для HomeController
/Views/Home/Index.cshtml
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
Cnt : @ViewBag.cnt
И запустить это приложение,
затем я получаю это сообщение об ошибке. =3
Я знаю, что писать долго, но я старался писать как можно больше деталей.
Если кто-нибудь знает, как решить эту проблему, пожалуйста, сообщите мне.
Спасибо!
[Трассировки стека]
[KeyNotFoundException: The given key was not present in the dictionary.]
System.Collections.Generic.Dictionary`2.get_Item(TKey key) +9619597
Advantage.Data.Provider.AdsProviderManifest.GetStoreType(TypeUsage edmType) +1150
System.Data.Entity.ModelConfiguration.Edm.Services.StructuralTypeMappingGenerator.MapTableColumn(EdmProperty property, DbTableColumnMetadata tableColumnMetadata, Boolean isInstancePropertyOnDerivedType, Boolean isKeyProperty) +60
System.Data.Entity.ModelConfiguration.Edm.Services.PropertyMappingGenerator.Generate(EdmEntityType entityType, IEnumerable`1 properties, DbEntitySetMapping entitySetMapping, DbEntityTypeMappingFragment entityTypeMappingFragment, IList`1 propertyPath, Boolean createNewColumn) +1293
System.Data.Entity.ModelConfiguration.Edm.Services.EntityTypeMappingGenerator.Generate(EdmEntityType entityType, DbDatabaseMapping databaseMapping) +496
System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.GenerateEntityTypes(EdmModel model, DbDatabaseMapping databaseMapping) +122
System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.Generate(EdmModel model) +30
System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) +189
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +58
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +117
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +453
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +57
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +37
System.Linq.Queryable.Count(IQueryable`1 source) +50
Ads_test_mvc3.Controllers.HomeController.Index() in C:\Users\mark\Documents\Visual Studio 2010\Projects\Ads_test_mvc3\Ads_test_mvc3\Controllers\HomeController.cs:20
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969117
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184