I saw the error below when trying to call the AcceptAllChanges() in "using"
"Entity" does not contain a definition for 'AcceptAllChanges' and no extension method 'AcceptAllChanges' accepting a first argument of type 'Entity' could be found (are you missing a using directive or an assembly reference?)
using (vbfEntity)
{
vbfEntity.Database.Connection.Open();
using (TransactionScope transaction = new TransactionScope())
{
//Operation code
}
if (src.status)
vbfEntity.AcceptAllChanges();
}
Can anybody help? Thank you.
AcceptAllChanges() is a method from the older ObjectContext API.
For EF6 and DBContext API use SaveChanges() or add this
ObjectContext obj = new ObjectContext("connstring");
obj.AcceptAllChanges();
Related
In MVVMCross's own guide to migrating from 4 to 5 they say this method should be as follows in the iOS Setup.cs class:
protected override IMvxIosViewPresenter CreatePresenter()
{
Forms.Init();
var xamarinFormsApp = new MvxFormsApp();
return new MvxFormsIosPagePresenter(Window, xamarinFormsApp);
}
However the MvxFormsApp class doesn't seem to exist anymore - and yes I have changed all the nuget dependances to the new ones
This is the error:
Error CS0246: The type or namespace name 'MvxFormsApp' could not be found (are you missing a using directive or an assembly reference?) (CS0246)
MVVMCross replied on Twitter that the class name has changed to MvxFormsApplication and the namespace it is in is MvvmCross.Forms.Core - so that has finally solved it. I have asked them to fix their migration instructions to give the correct class names and perhaps a note about the namespace
MVC3 EF5. It's running well. But when I update model from database, builds successfully but I got the exception above on the last line. When I last updated from database it was 2-3 months ago, and it was fine.
public static ObjectContext GetContext()
{
Assembly testAssembly = Assembly.GetExecutingAssembly();
Type calcType = testAssembly.GetType("Model.Entities");
return (ObjectContext)Activator.CreateInstance(calcType);
}
Newer versions of Entity Framework provide DbContext, as opposed to the ObjectContext that was <= EF 4.0. However, it is still possible to return a reference to the ObjectContext via IObjectContextAdapter
Assembly testAssembly = Assembly.GetExecutingAssembly();
Type calcType = testAssembly.GetType("Model.Entities");
var entities = (DbContext)(Activator.CreateInstance(calcType));
return ((IObjectContextAdapter)entities).ObjectContext;
Personally however, I would instead look at upgrading your code to return the DbContext, as it is more advanced.
I have just started experimenting with Web Api 2 and StructureMap, having installed StructureMap.MVC4 Nuget package. Everything seems to work fine until I tried to register a user. I got this error when this implementation of IHttpControllerActivator tried to instantiate a controller:
public class ServiceActivator : IHttpControllerActivator
{
public ServiceActivator(HttpConfiguration configuration) { }
public IHttpController Create(HttpRequestMessage request
, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var controller = ObjectFactory.GetInstance(controllerType) as IHttpController;
return controller;
}
}
The error I got was:
StructureMap Exception Code: 202
No Default Instance defined for PluginFamily Microsoft.AspNet.Identity.IUserStore`1[[Microsoft.AspNet.Identity.EntityFramework.IdentityUser, Microsoft.AspNet.Identity.EntityFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], Microsoft.AspNet.Identity.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
I understand what the error is, but not entirely sure how to solve it. Is it correct to assume the default scanner in StructureMap could not find a default implementation of IUserStore? Here's the initialisation code I used:
ObjectFactory.Initialize(x => x.Scan(scan =>
{
scan.AssembliesFromApplicationBaseDirectory();
scan.WithDefaultConventions();
}));
Any ideas please? Thanks.
EDIT:
I think I may have solved the initial issue using this:
x.For<Microsoft.AspNet.Identity.IUserStore<IdentityUser>>()
.Use<UserStore<IdentityUser>>();
But now there's another default instance StructureMap couldn't work out - the dbcontext. Here's the next error message I'm getting:
ExceptionMessage=StructureMap Exception Code: 202
No Default Instance defined for PluginFamily System.Data.Entity.DbContext, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Now I'm really lost...
The WithDefaultConventions() call won't pick up your DbContext and AspNet Identity implementations. You'll want to look at some of the other methods like SingleImplementationsOfInterface() and ConnectImplementationsToTypesClosing.
By default when I setup my StructureMap container, I will do the following configuration in order to ensure that StructureMap will always resolve the interfaces and base classes of my preferred class to my actual preferred class:
ioc.For<MyDbContext>().HybridHttpOrThreadLocalScoped().Use<MyDbContext>();
ioc.For<DbContext>().HybridHttpOrThreadLocalScoped().Use<MyDbContext>();
For the new AspNet Identity classes, just subclass the generic classes they give you out of the box:
public class MyUserManager : UserManager<MyUser> { }
public class MyUserStore : UserStore<MyUser> { }
And then again, make sure StructureMap knows about these:
ioc.For<IUserStore<MyUser>>().Use<MyUserStore>();
ioc.For<UserStore<MyUser>>().Use<MyUserStore>();
ioc.For<UserManager<MyUser>>().Use<MyUserManager>();
Generally, you don't have to explicitly register every class with StructureMap, but with my DbContext and Identity classes, I prefer to have those explicity registered for maintenance purposes.
ericb: I can see the purpose of what you've posted but I can't quite get it to work. The MyUserManager class declaration "public class MyUserManager : UserManager { }" is complaining that the UserManager interface does not contain a constructor that takes 0 arguments?
Any help would be greatly appreciated!
Ps. This is by no means an answer but I'm not qualified enough to simply comment on your answer unfortunately!
Update: Found a solution here: Dependency Injection Structuremap ASP.NET Identity MVC 5
For clarity we replaced any of the above with the following in the IoC file:
x.For<Microsoft.AspNet.Identity.IUserStore<ApplicationUser>>()
.Use<Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>>();
x.For<System.Data.Entity.DbContext>().Use(() => new ApplicationDbContext());
I'm sure we're missing out on some extra benefits that ericb gets with his solution but we're not utilising anything that would take advantage of them.
There is a quick and easy workaround to this problem as well, and in many cases may be sufficient. Go to AccountController.cs and above the default constructor (the one with no params or code in it) add [DefaultConstructor] and resolve using structuremap.
[DefaultConstructor]
public AccountController()
{
}
Though the proper IoC solution is this...
For<IUserStore<ApplicationUser>>().Use<UserStore<ApplicationUser>>();
For<DbContext>().Use<ApplicationDbContext>(new ApplicationDbContext());
For<IAuthenticationManager>().Use(() => HttpContext.Current.GetOwinContext().Authentication);
Or you can try constructor injection method:
x.For<IUserStore<ApplicationUser>>().Use<UserStore<ApplicationUser>>()
.SelectConstructor(() => new UserStore<ApplicationUser>(new MyContext()));
private void EnsureCurrentlyValid()
{
//I'm valid if IDataErrorInfo.this[] returns null for every property
var propsToValidate = new[] { "Name", "Email", "Phone", "WillAttend" };
bool isValid = propsToValidate.All(x => this[x] == null);
if (!isValid)
throw new InvalidOperationException("Can't submit invalid GuestResponse");
}
'System.Array' does not contain a definition for 'All' and no extension method 'All' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?) C:\dev\aspnet\PartyInvites\Models\GuestResponse.cs
What am I missing?
Add this to the top of your file:
using System.Linq;
All is an extension method defined on Enumerable. The extension methods (including All) are defined in the System.Linq namespace, so you need to include a using directive for System.Linq to your class in order to reference the extension methods. You'll also need to be using C# 3.0 and .NET 3.5.
I'm trying to implement the repository pattern using a generic repository like the one found here: Implementing Repository Pattern With Entity Framework
I've created a test suite (I'm using NUnit) to test the repository but I've been having issues. Here's the error I'm getting:
MyBusiness.Test.Domain.RepositoryTest.SelectCol:
System.Data.EntitySqlException :
'ColCoordinate' 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.
I believe it's coming from this method:
public ObjectQuery<E> DoQuery()
{
return _ctx.CreateQuery<E>("[" + typeof(E).Name + "]");
}
I've made sure to add the reference at the top of the page:
using MyBusiness.Domain.DomainModel.EntityFramework;
Here's my test setup and test method:
Repository<ColCoordinate, ObjectContext> _colRepository = null;
ObjectContext _context = null;
EntityContextCreator contextCreator = null;
[SetUp]
public void SetUp()
{
contextCreator = new EntityContextCreator();
_context = contextCreator.Create();
_colRepository = new Repository<ColCoordinate, ObjectContext>(_context);
}
[Test]
public void SelectCol()
{
IList<ColCoordinate> colList = _colRepository.SelectAll();
Assert.True(colList.Count > 0);
}
Anyone know why I'm getting this error or have any suggestions as to how to fix it?
If you need more information please ask and I'll update the question.
Thanks,
Matt
Well the code you identified:
public ObjectQuery<E> DoQuery(){
return _ctx.CreateQuery<E>("[" + typeof(E).Name + "]");
}
Is very suspect, the TypeName is not what is required, you need the EntitySet name, sometimes they are the same thing, but often they are not, especially if you've manually updated your model to have more readable properties.
For example if you have:
ctx.Customers which returns a type called Customer, the typename is Customer the EntitySet name is Customers.
Tip 13 in my series of tips has some code that shows you how to get the EntitySet name from a Type.
Hope this helps
Alex