Exceptions for Entity Framework Code First Migrations - c#

I'm getting several unhandled exceptions while using Code First Migrations of Entity Framework 4.3.
The database context:
public class MyAppContext : DbContext
{
public DbSet<Branch> Branches { get; set; }
public MyAppContext()
{ }
}
The entity:
public class Branch : IEntity<Guid>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Active { get; set; }
}
The database initializer:
public class MyAppInitializer : CreateDatabaseIfNotExists<MyAppContext>
{
protected override void Seed(MyAppContext context)
{
context.Branches.Add(new Branch() { Id = branchId, Name = "Acme", Description = "Acme", Active = true });
context.SaveChanges();
}
}
I installed Entity Framework 4.3 to my DAL project and MVC project using:
Install-Package EntityFramework
I have set the MVC project as the startup project and executed the following command to the DAL project with the database context and initializer:
PM> Enable-Migrations -Verbose
Using NuGet project 'Ckms.KeyManagement.Managers'.
Error while searching for context type (specify -Verbose to see exception details).
System.Data.Entity.Migrations.Design.ToolingException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. at
System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
runner) at
System.Data.Entity.Migrations.Design.ToolingFacade.GetContextTypes()
at
System.Data.Entity.Migrations.MigrationsCommands.FindContextToEnable()
Edit the generated Configuration class to specify the context to
enable migrations for.
Code First Migrations enabled for project Ckms.KeyManagement.Managers.
A DbMigrationsConfiguration child class is added to the DAL project. If I add the type of the DbContext manually and enable Automatic Migrations:
internal sealed class Configuration : DbMigrationsConfiguration<MyAppContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MyAppContext context)
{ }
}
These exceptions are thrown for the Add-Migration and Update-Database commands:
PM> Add-Migration TestEFMigrationsColumn -Verbose
Using NuGet project
'Ckms.KeyManagement.Managers'. Using StartUp project ''.
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.ArgumentException: The
parameter is incorrect. (Exception from HRESULT: 0x80070057
(E_INVALIDARG)) --- End of inner exception stack trace --- at
System.RuntimeType.InvokeDispMethod(String name, BindingFlags
invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers,
Int32 culture, String[] namedParameters) at
System.RuntimeType.InvokeMember(String name, BindingFlags
bindingFlags, Binder binder, Object target, Object[] providedArgs,
ParameterModifier[] modifiers, CultureInfo culture, String[]
namedParams) at
System.Management.Automation.ComMethod.InvokeMethod(PSMethod method,
Object[] arguments) Exception has been thrown by the target of an
invocation.
Update-Database:
PM> Update-Database -Verbose
Using NuGet project
'Ckms.KeyManagement.Managers'. Using StartUp project ''.
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.ArgumentException: The
parameter is incorrect. (Exception from HRESULT: 0x80070057
(E_INVALIDARG)) --- End of inner exception stack trace --- at
System.RuntimeType.InvokeDispMethod(String name, BindingFlags
invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers,
Int32 culture, String[] namedParameters) at
System.RuntimeType.InvokeMember(String name, BindingFlags
bindingFlags, Binder binder, Object target, Object[] providedArgs,
ParameterModifier[] modifiers, CultureInfo culture, String[]
namedParams) at
System.Management.Automation.ComMethod.InvokeMethod(PSMethod method,
Object[] arguments) Exception has been thrown by the target of an
invocation.
Any ideas? The error messages are not really helpful. I have tried the Nuget commands with and without an existing database.

If you are using separate library for data access you need to provide it name when running query:
Add-Migration -StartUpProjectName "Your DAL Project" MyNewMigration
Update-Database -StartUpProjectName "Your DAL Project" -Verbose

add-migration -Name First -ProjectName DbSet.Framework -StartUpProjectName CodeFirstConsole
First: Name of Migration
Dbset.Framework: Project where dbContext and other classes
CodeFirstConsole: Start Up project (could be your web, windows or console app)

For System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) adding -projectname and startupprojectname did not help.
Setting the PackageManager Console's "Default Project" Dropdown to point to the Library (in my case) where I wanted the "Migration folder" and its expected contents to be was the only way to get this running from a multiproject solution.

I also had the same issue. Found out that if anything is wrong with the config files this error comes up. I had duplicate tags in web.config and removing these solved my issue.

I had solve this problem only by changing the name used in connection string.
<add name="abcd" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
And I use connectionStrings after closing tag of the
appSettings
and just before starting tag of
system.web
Make sure that name that you use in connectionString not used in other connections.

Ran into the same problem , solved by removing <globalization> from web.config.

You must be having two connection strings in your web. Config files. Just delete one

Related

Constructor injection not working in .NET 4.7.2 Dependency Injection in ASP.NET WebForms

I used article "Use Dependency Injection In WebForms Application" https://devblogs.microsoft.com/aspnet/use-dependency-injection-in-webforms-application/
The project retargeted to .NET Framework 4.7.2 in project properties and in web.config:
<system.web>
<httpRuntime targetFramework="4.72" ...
AspNet.WebFormsDependencyInjection.Unity NuGet package is installed.
Type is registered in Global:
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
var container = this.AddUnity();
container.RegisterType<IVCRole, eVCRole>();
}
...
I checked container and it is working and registering interface IVCRole mapping to class eVCRole.
Default.aspx.cs is refactored:
public partial class Default : System.Web.UI.Page
{
private IVCRole vcr;
public Default(IVCRole avcr)
{
vcr = avcr;
}
protected void Page_Load(object sender, EventArgs e)
{
...
But when I run web application there is an error
"Constructor on type 'ASP.default_aspx' not found."
If I add this constructor:
public partial class Default : System.Web.UI.Page
{
private IVCRole vcr;
public Default() {}
public Default(IVCRole avcr)
{
vcr = avcr;
}
protected void Page_Load(object sender, EventArgs e)
{
...
the constructor for DI
public Default(IVCRole avcr)
{
vcr = avcr;
}
is never called and "vcr" is always null in Page_Load.
There is an article: "Dependency Injection in ASP.NET Web Forms":
https://makingloops.com/dependency-injection-in-web-forms/
where this error is mentioned:
"On occasion you may see a build error complaining about the lack of a zero-argument constructor on the page. I notice that this error will magically go away depending on the context. Someone else suggested using property injection with the Dependency attribute on pages to get around this, but i didn’t find that was necessary."
But in my case there is no "magic".
There is similar question in Stackoverflow:
.NET 4.7.2 Dependency Injection in ASP.NET WebForms Website - Constructor injection not working
But in my case property injection is not working:
public partial class Default : System.Web.UI.Page
{
[Dependency]
public IVCRole vcr { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
...
"vcr" in Page_Load is still null.
There is solution to get it working with custom implementation of DI provider but I already using .NET 4.7.2 an Unity. Author mentioned that for web application should not be any problem as the problem is with website compiler.
How to get DI constructor or property injection to working in Default page using .NET 4.7.2 and Unity?
This is Stack:
[MissingMethodException: Constructor on type 'ASP.default_aspx' not found.]
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) +1173
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +130
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) +21
Microsoft.AspNet.WebFormsDependencyInjection.Unity.ContainerServiceProvider.DefaultCreateInstance(Type type) +17
Microsoft.AspNet.WebFormsDependencyInjection.Unity.ContainerServiceProvider.GetService(Type serviceType) +161
__ASP.FastObjectFactory_app_web_mmaneivx.Create_ASP_default_aspx() in c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\vs\19e4d468\8c7800a0\App_Web_mmaneivx.2.cs:0
System.Web.Compilation.BuildResultCompiledType.CreateInstance() +31
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +104
System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +33
System.Web.UI.PageHandlerFactory.GetHandler(HttpContext context, String requestType, String virtualPath, String path) +39
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +386
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
Disclaimer: I maintain this NuGet package and project that use Microsoft.Extensions.DependencyInjection for ASP.NET WebForms (and MVC, SignalR and WCF) in the .NET Framework 4.7.2 - however the content of this post isn't specific to my implementation of DI for ASP.NET.
Check your .csproj:
Ensure you're targeting .NET Framework 4.7.2 or later (note that many shared web-hosts - including Azure App Services - may be running older versions of the .NET Framework):
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
Check your web.config
Ensure you have <system.web><compilation targetFramework="4.7.2">
Ensure you have <system.web><httpRuntime targetFramework="4.7.2"/>
If you have <assemblies><clear /> ensure you have <add assembly="*"/> after the <clear /> or otherwise ensure you're explicitly listing all required assemblies in <add /> elements.
Your ConfigureServices method (or anything that configures DI) must run before Global.asax's Application_Start!
Currently your code is instantiating the Unity container as a local inside Application_Start - this is a bad idea (as you aren't preserving a strong-reference in a field - a bug elsewhere could cause the GC to collect your DI container, which would be a bad thing.
You also need to add a IHttpModule to support scoped DI containers (my package does this for you already).
This is done by using the PreApplicationStartMethod attribute (from WebActivatorEx.
Note that PreApplicationStartMethod is not the same as OWIN's [assembly: Microsoft.Owin.OwinStartup() attribute! Your project may need to use both if you're using DI with SignalR.
Your Startup class code should look like this:
[assembly: PreApplicationStartMethod ( typeof( global::MyProject.RssStartup ), methodName: nameof( global::MyProject.MyStartup.OnPreStart ) )]
namespace MyProject
{
internal static class MyStartup
{
internal static void OnPreStart()
{
// Set-up your DI system here and then call your `ConfigureServices` method before this method returns.
}
}
}
I had exactly the same problem (exception MissingMethodException: Constructor on type 'ASP.*my_page*_aspx' not found.) and it turned out that there was error in creating inner dependency.
I mean, I had:
public class Global : System.Web.HttpApplication
{
private IUnityContainer container;
protected void Application_Start(object sender, EventArgs e)
{
container = this.AddUnity();
container.RegisterType<IDataStorage>(
new InjectionFactory(c => DataStorageBuilder.GetDefaultStorage()));
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
and Page:
public partial class Contact : System.Web.UI.Page
{
private IDataStorage storage { get; set; }
public Contact(IDataStorage storage)
{
this.storage = storage;
}
protected void Page_Load(object sender, EventArgs e)
{
storage.DoRequest();
}
}
And DataStorageBuilder.GetDefaultStorage() actually threw exception, which Unity wrapped in Constructor on type 'ASP.contact_aspx' not found.
So maybe, you need to check that container can correctly create all inner dependencies of page (in your example it is eVCRole).
For me the solution was to remove optimizeCompilations="true" from:
<system.web>
<compilation debug="true" targetFramework="4.8" optimizeCompilations="true">
</compilation>
</system.web>
in Web.Config
I had a very similar issue as the above answer by Света Нестерова https://stackoverflow.com/a/65205408/6901318
One of the dependencies I was trying to register was from an internally maintained Nuget package.
For whatever reason, it is not able to register the type when it is defined in a dll like that. I have done this with .Net Core and it works fine. I am assuming that those references have not been resolved at this point in the application startup. I could be wrong though. It is just a guess, if anyone knows please comment on it.
I ended up making an empty class that inherited from the class I wanted to inject. And, that also implemented the interface that was defined in the NuGet package.
public interface IADAuthenticationManager: IADManager
{
}
IADAuthenticationManager is the wrapper interface and IADManager is the interface defined in the package.
public class ADAuthenticationManager: ADManager, IADAuthenticationManager
{
public ADAuthenticationManager(IADProvider aDProvider, IErrorLogger logger) :
base(aDProvider, logger)
{
}
}
ADAuthenticationManager is the wrapper class. ADManager is the class that implements IADManager and is also defined in the NuGet package. IADAuthenticationManager is the wrapper interface from above.
In my Global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
...
var container = this.AddUnity();
...
container.RegisterType<IADManager, ADAuthenticationManager>();
container.RegisterType<IADAuthenticationManager, ADAuthenticationManager>();
}
The classes in the NuGet package also had some dependencies that needed wrapper classes created as well. It was a process. But, everything is working now.

add migration failed when DbContext in sperate project

I have a project with different layers: web, services, model, data each one has a different project in the same solution. The application, compiles and runs OK. But when I tried to implement migration I got the following error
dnx . ef migration add MigrationFile
System.InvalidOperationException: No DbContext was found. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.
at Microsoft.Data.Entity.Commands.ContextTool.SelectType(IEnumerable`1 types, String name)
at Microsoft.Data.Entity.Commands.MigrationTool.GetContextType(String name)
at Microsoft.Data.Entity.Commands.MigrationTool.AddMigration(String migrationName, String contextTypeName, String startupAssemblyName, String rootNamespace,String projectDir)
at Microsoft.Data.Entity.Commands.Program.<>c__DisplayClass12_0.<AddMigration>b__0()
at Microsoft.Data.Entity.Commands.Program.Execute(String startupProject, Func`1 invoke)
at Microsoft.Framework.Runtime.Common.CommandLine.CommandLineApplication.Execute(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at Microsoft.Framework.ApplicationHost.Program.ExecuteMain(DefaultHost host,String applicationName, String[] args)
at Microsoft.Framework.ApplicationHost.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at dnx.host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env, FrameworkName targetFramework)
at dnx.host.RuntimeBootstrapper.ExecuteAsync(String[] args, FrameworkName targetFramework)
at dnx.host.RuntimeBootstrapper.Execute(String[] args, FrameworkName targetFramework)
I'm using this answer as a reference.
Maybe your project has more than one DbContext or you have not turned on the migrations.
If you have more than one Context, you will want to enable and add migrations for each Context separately:
add-migration -ConfigurationTypeName MyProject.MigrationsFolder.Configuration "migrationName"
This code will add a new Migration based on your Context and using the Configuration class associated to it. The following code will update the database associated with the Configuration class.
update-database -ConfigurationTypeName MyProject.MigrationsFolder.Configuration
the commands must be like this
- dnu restore
cd the project which contain the context path
dnx . ef migration add -c ContextName - s StartupProjectName
try it and if this work let me know, thnx ^^

ResolutionFailedException with Unity

I'm using Patterns and Practices' Unity to inject dependencies into my objects and have hit a weird (to me, anyway) issue. Here's my class definitions:
public class ImageManager : IImageManager
{
IImageFileManager fileManager;
public ImageManager(IImageFileManager fileMgr)
{
this.fileManager = fileMgr;
}
}
public class ImageFileManager : IImageFileManager
{
public ImageFileManager(string folder)
{
FileFolder = folder;
}
}
And here's the code to register my classes
container.RegisterInstance<MainWindowViewModel>(new MainWindowViewModel())
.RegisterType<IPieceImageManager, PieceImageManager>(
new InjectionConstructor(typeof(string)))
.RegisterType<IImageFileManager, ImageFileManager>()
.RegisterType<IImageManager, ImageManager>(
new InjectionConstructor(typeof(IImageFileManager)));
I originally resolved this in the code behind (I know, it defeats the purpose. Bear with me.) of the XAML file like this
IImageManager imageManager = MvvmViewModelLocator.Container.Resolve<IImageManager>(
new ParameterOverride("folder", "/images"));
And it worked. But I created a view model for my main view and when I copied the same line into it, I get an exception. Here are the two most inner exceptions:
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
HResult=-2146233088
Message=Resolution of the dependency failed, type = "SwapPuzzleApp.Model.IImageManager", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type IImageManager does not have an accessible constructor.
At the time of the exception, the container was:
Resolving SwapPuzzleApp.Model.IImageManager,(none)
Source=Microsoft.Practices.Unity
TypeRequested=IImageManager
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
at SwapPuzzleApp.ViewModel.MainWindowViewModel..ctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MainWindowViewModel.cs:line 17
at SwapPuzzleApp.ViewModel.MvvmViewModelLocator..cctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MvvmViewModelLocator.cs:line 51
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The type IImageManager does not have an accessible constructor.
Source=Microsoft.Practices.Unity
StackTrace:
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:
I'm not sure what the problem is, as ImageManager clearly has a public constructor. I thought it might be due to an invalid path, but if I concretely instantiate the object, everything works.
// this line has no problems
IImageManager imageManager = new ImageManager(new ImageFileManager("/images"));
I also wondered if I needed to pass in new InjectionConstructor(typeof(string)) when I register IImageManager, but it doesn't seem to help and why would it be needed now and not before? So I'm stumped. This is my first attempt at using Dependency Injection, so it's probably something basic. I'm just not seeing what, though.
Look very closely at the error message. Notice this part:
Message=The type IImageManager does not have an accessible constructor.
Notice the type name is IImageManager, not ImageManager. Somewhere along the line you lost your type mapping.
Your registration of FileImageManager has a problem as well, since you don't specify the folder parameter in the registration, so Unity has no idea what string to pass.
I was using the examples in this article as my guide. Either the examples in there are way too advanced for an introduction, or there's misinformation in that topic.
After consulting other sources (mainly PluarlSight), I came up with a much simpler and more logical solution.
container.RegisterInstance<TimerViewModel>(new TimerViewModel());
container.RegisterType<IPieceImageManager, PieceImageManager>();
container.RegisterType<IImageFileManager, ImageFileManager>
(new InjectionConstructor("/images"));
container.RegisterType<IImageManager, ImageManager>();
I ran into a similar issue with this error tied directly to a Mock (using automoq) that I was doing for an operation. In this case it turned out that because there were a number of member methods that get called with the object being mocked, that I had to define all of those in the automoq chain to get it to resolve properly
I realize this is an example in instance code, but it could occur in Moqs also. So if you read this and are wondering about an example related to Moqs, look into that first.

Telerik.OpenAccess.OpenAccessException was unhandled by user code

The following is error I am getting. Please help on this.
Telerik.OpenAccess.OpenAccessException was unhandled by user code
Message=No metadata has been registered for class Ind.Data.IndiStage.Academy. (This usually indicates, that either this class is not declared persistent or it is declared persistent but not enhanced. The class was loaded from file:///C:/Users/suresh/Documents/WorkSpace/Ind_folder/Ind.ETLService/bin/Release/Ind.Data.IndiStage.DLL.)
Source=Telerik.OpenAccess
CanRetry=true
StackTrace:
at Telerik.OpenAccess.SPI.Backends.ThrowException(Exception e)
at OpenAccessRuntime.ExceptionWrapper.Throw()
at OpenAccessRuntime.storagemanager.StorageManagerFactoryBuilder.createSmfForURL()
at OpenAccessRuntime.storagemanager.StorageManagerFactoryBuilder.createStorageManagerFactory()
at OpenAccessRuntime.DataObjects.PersistenceManagerFactoryImp.createStorageManagerFactory()
at OpenAccessRuntime.DataObjects.PersistenceManagerFactoryBase.init()
at OpenAccessRuntime.DataObjects.PersistenceManagerFactoryImp.init()
at OpenAccessRuntime.DataObjects.PersistenceManagerFactoryImp..ctor(PropertySet properties, Object classloader)
at OpenAccessRuntime.DataObjects.PersistenceManagerFactoryImp.getPersistenceManagerFactory(PropertySet props)
at OpenAccessRuntime.DataObjects.BootstrapPMF.getPersistenceManagerFactory(PropertySet props)
at OpenAccessRuntime.Helper.getPersistenceManagerFactory(PropertySet props)
at OpenAccessRuntime.DatabaseAdapter.AssertPersistenceManagerFactory(String usr, String password, Boolean open)
at OpenAccessRuntime.DatabaseAdapter.GetObjectScope(TransactionProvider provider)
at Telerik.OpenAccess.Database.GetObjectScope(TransactionProvider provider)
at Telerik.OpenAccess.OpenAccessContextBase.GetScope()
at Telerik.OpenAccess.OpenAccessContext.GetAllCore[T]()
at Telerik.OpenAccess.OpenAccessContext.GetAll[T]()
at System.Timers.Timer.MyTimerCallback(Object state)
InnerException:
wow.
I got a hardtime to get rid of this exception. "No metadata has been registered for class" with Telerik OpenAccess.
read this article especially you use CI build system like TeamCity: http://docs.telerik.com/data-access/developers-guide/integrating-data-access-in-your-solution/external-tools-howto-integrate-enhancer-msbuild

EF and Webservice Error "System.InvalidOperationException"

I started a new project. Created a class library added EF item to it under a DB namespace and then create a class(Stripped down) for each entity that i can expose in WS. I ref the CL in a windows test app to see if everything was working and it was.So i created a WS add reference addedd the connectionstring for EF and then created a webmethod that retruns the object i created for each entity.
so my namspaces looks like this
[projectName].CL.Item - created object
[projectName].CL.DB.Item - Ef Item
[projectName].WS - Webservice namespace
So i ran the ws and tested it. and i get this lovely little exception.
System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Evidence evidence)
at System.Web.Services.Protocols.XmlReturn.GetInitializers(LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.XmlReturnWriter.GetInitializers(LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.MimeFormatter.GetInitializers(Type type, LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.HttpServerType..ctor(Type type)
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProc
Now this tells me it need reference to data.entity so i added still thinking to myself this is weird never had to do this and i am not return entity object i am returning the created onces but i did it. still the same error
then i saw that no matter what webmethod i select it does this i commented the webmethod out and made a helloworld and it worked.
I looked on google some people suggestthat you add
<add assembly="System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
to the webconfig i did and still same error. i am dumbfounded i do this sort of thing like daily and i never got a error like this. And the EF structure is nothing special 5 tables with foreignkeys.
i even deleted the WS/CL project and recreated it.
pls help
Found the problem...
I have in each POCO class this
namespace CL
{
public class Item
{
public static implicit operator Item(DB.Item db)
{
return new Item
{
Created = db.Created,
Id = db.ItemId
};
}
}
}
that basically converts the DB item into a POCO item.
So if i do this instead
namespace CL.DB
{
public partial class Item
{
public static implicit operator CL.Item(Item db)
{
return new CL.Item
{
Created = db.Created,
Id = db.ItemId
};
}
}
}
it works fine. WTF

Categories