How do I resolve "No views were found in assemblies or could be generated for Table"? - entity-framework

I am working with a database first model in Entity Framework 5 and when I attempt to add a row, I get the following error:
"No views were found in assemblies or could be generated for Table 'ui_renewals'."
The table exists in my EDMX and the template generated a ui_renewals class. I've deleted the table from the EDMX and added it again using the Update Model from Database option and I get the same error. Creating a separate connection for it resolves the issue, but that seems like a less-than-ideal solution (more like a kludge) not to mention it makes it more difficult to maintain in the future.
Any ideas on how to fix this so that I can add or update (I've tried both) a row in ui_renewals?
Here is the code I'm currently using - only difference before was using db as a DBContext instead of ui (yes, receipt is misspelled - gotta love legacy stuff)
[HttpPost]
public bool UpdateTeacher(string login_id, string password, UIRenewal data)
{
if (ModelState.IsValid)
{
// map from UIRenewal VM to ui_renewal
ui_renewals Renewal = Mapper.Map<UIRenewal, ui_renewals>(data);
// check to see if this is a new entry or not
var tmp = ui.ui_renewals.Find(Renewal.reciept);
if (tmp == null)
ui.ui_renewals.Add(Renewal);
else
{
// mark as modified
db.Entry(Renewal).State = EntityState.Modified;
}
// save it
try
{
ui.SaveChanges();
}
catch (DBConcurrencyException)
{
return false;
}
return true;
}
return false;
}
I should mention that I do have a view in the model (v_recent_license).

I know this is a very old question, however as I haven't found any other topics like this, I'll post my answer.
I have had the same Exception thrown. I found that, in a failed attempt to optimize EF performance, following the advices found here, I left behind this piece of code in EF .edmx code-behind:
<EntityContainerMapping StorageEntityContainer="XXXModelStoreContainer" CdmEntityContainer="YYYEntities" GenerateUpdateViews="false">
I removed the GenerateUpdateViews="false" string, and all is working again.
(The Exception message is a little misleading in my opinion).

Related

System.InvalidOperationException: Relational-specific methods can only be used when the context is using a relational database provider

System.InvalidOperationException:
Relational-specific methods can only be used when the context is using a relational database provider.
Getting the above mentioned error while using InMemoryDatabase for Test Case?
var msaContextOptions = new DbContextOptionsBuilder<MSA.DAL.MsaDbContext>()
.UseInMemoryDatabase(databaseName: "Get results")
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.Options;
Comparing with provider string is brittle - what if Microsoft changes to Microsoft.EntityFramework as it moves away from Core!
I would recommend to use
if (!context.Database.IsInMemory())
{
context.Database.Migrate();
}
or
if (context.Database.IsRelational())
{
context.Database.Migrate();
}
we have EF-related code in a separate nuget package that doesn't include Microsoft.EntityFrameworkCore.InMemory, therefore first option doesn't work for us.
As mentioned by other people I found skipping DBMigration is the best option for now.
I am running Database Migration when Database ProviderName is not InMemory.
if (context.Database.ProviderName != "Microsoft.EntityFrameworkCore.InMemory")
{
context.Database.Migrate();
}
In our case, the solution of #hemant-sakta didn't work. The cause for the error was that we set the auto-increment value in one of our database tables on seeding (we seed during migration).
The solution was to skip setting the auto-increment value when in Isolated Mode:
private static void SetAutoIncrementValue(MyContext context)
{
if (HostingEnvironment.IsEnvironment("Isolated")) return;
// auto increment code
}

The model backing the 'DataContext' context has changed since the database was created

I am trying to use Code First with Migrations. Even though there are no current changes to my model, I'm getting an exception. When I add a migration, the up and down are empty, but I get a runtime error with the message as follows:
An exception of type 'System.InvalidOperationException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: The model backing the 'MyDataContext' context
has changed since the database was created. Consider using Code First
Migrations to update the database (http://go.microsoft.com/fwlink/?
My architecture is as follows:
DataAccess project that includes the context, fluid configurations and migrations code
Model project that contains the poco classes
Web API and MVC projects that each contain the connections string in their respective web.config files.
Additionally I have the following code:
DbInitializer
public static MyDataContext Create()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDataAccess.MyDataContext, MyDataAccess.Migrations.Configuration>());
return new MyDataContext(ConfigurationManager.ConnectionStrings["MyDataContext"].ConnectionString, null);
}
I started with AutomaticMigrationsEnabled = false; in the migration Configuration constructor, as it was my understanding that this would allow (and require) me to have more control over when migrations were applied. I have also tried setting this to true but with the same result.
I added a new migration upon receiving this error, and the Up method was empty. I updated the database to this new migration, and a record was created in the _migrationHistory table, but I still receive the error when I attempt to run the application. Also, the seed data was not added to the database.
protected override void Seed(MyDataAccess.MyDataContext context)
{
IdentityResult ir;
var appDbContext = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(appDbContext));
ir = roleManager.Create(new IdentityRole("Admin"));
ir = roleManager.Create(new IdentityRole("Active"));
ir = roleManager.Create(new IdentityRole("InActive"));
var userNamager = new UserManager<User>(new UserStore<User>(appDbContext));
// assign default admin
var admin = new User { UserName = "administrator", Email = "myAdmin#gmail.com" };
ir = userNamager.Create(admin, "myp#55word");
ir = userNamager.AddToRole(admin.Id, "Admin");
}
where
public class ApplicationDbContext : IdentityDbContext<User>
{
public ApplicationDbContext()
: base("MyDataContext", throwIfV1Schema: false)
{
}
...
The question: If Add-Migration isn't seeing any change in the model, why do I get this error when I run? Why isn't the seed code being hit? How do I fix this, or if that can't be determined, how do I further determine the root cause?
I am not sure if you found the answer to your problem, but this other answer I found here actually did it for me:
Entity Framework model change error
I actually ended up deleting the __MigrationHistory table in SQL Server which I didn't know it was being created automatically.
The article also talks about the option to not generate it I think by using this instruction: Database.SetInitializer<MyDbContext>(null); but I have not used it, so I am not sure if it works like that
This worked for me.
Go to Package Manager Console and Run - Update-Database -force
I bet your data context is not hooking up the connection string.
Check if it's not initialized with a localdb (something like (localdb)\v11.0) and not working with that when you might think it's set to something else.
My issue ended up being a conflict between Automatic Migrations being enabled and the initializer MigrateDatabaseToLatestVersion as described here.

Update issue with Generic Repositories using EF

I have created Generic Repository and I have two entities that i need to update in a transaction.
Here is what i m doing..
ProductOrganizationEntity poDataContext= new ProductOrganizationEntity();
IRepository<tblProductInfo> productRepo = new GenericRepository<ProductOrganizationEntity, tblConfirmation>(poDataContext);
Piece of Code which is causing problem is this.
using (TransactionScope txScope = new TransactionScope())
{
productRepo.Attach(productEntity);
productRepo.SaveChanges();
new ProductLocation().SaveLocation(productEntity.Locations, productEntity.productCode);
txScope.Complete();
}
productRepo.SaveChanges(); This is where it throws me Error. The error is
The operation could not be performed because OLE DB provider "SQLNCLI10" for linked server "Venus" was unable to begin a distributed transaction.
(We do have server named Venus but its not access in anyway in these transactions at all. Secondly as i said this works without transaction block).
This piece of code works fine if taken out from Transaction Block.
ProductLocation.SaveLocation is creating Repository for Location . Here is the code from Save Location.
IRepository<LocationInfo> locRepo= new GenericRepository<ProductOrganizationEntity, LocationInfo>(new ProductOrganizationEntity());
if (loc.locID <= 0) // This is a new Location to be added.
locRepo.Add(locEntity);
else
locRepo.Attach(siteToAdd);
locRepo.SaveChanges();
Here is what i have done in my generic repository for thse methods
public void Attach(TEntity entity)
{
if (entity == null)
throw new ArgumentException("Update : Supplied Entity is Null.");
_currentDbSet.Add(entity);
System.Data.Entity.Infrastructure.DbEntityEntry entry = _dataContext.Entry(entity);
entry.State = System.Data.EntityState.Modified;
}
and this is what i have in SaveChanges in my generic repo.
public virtual void SaveChanges()
{
if (_dataContext == null)
throw new Exception("SaveChanges: DataContext is not initialized.");
_dataContext.SaveChanges();
}
What is that i am doing wrong here .
I appreciate any pointers.
It might be possible that your server is linked to another SQL server at the database level.
Perhaps look at this: http://msdn.microsoft.com/en-us/library/ms188279.aspx
Must admit I've never used linked servers (not yet at least), but seeing "Linked Servers" in the error made me think of this.

ADO.NET Entity Data Model Designer extension-InvalidOperationException

Searching in internet I found this page:
http://connect.microsoft.com/VisualStudio/feedback/details/585738/exception-in-entity-data-model-designer-extension-a-property-extension-cannot-edit-an-item-in-an-entity-framework-namespace
I have a similar problem. I’m trying to modify the structure of the .edmx file adding a complexType but this cause that throw a InvalidOperationException . I thought that creating a scope this problem would be avoided but was not the case. This is a piece of code I'm using:
public void AddComplexTypeToConceptualModel(XElement document, XElement entityType)
{
XElement lastEntityType = document.Descendants(XName.Get("EntityType", "http://schemas.microsoft.com/ado/2008/09/edm")).LastOrDefault();
if (lastEntityType != null)
{
using (EntityDesignerChangeScope scope = Context.CreateChangeScope("Create ComplexType in Conceptual Model"))
{
lastEntityType.AddAfterSelf(CreateComplexType(entityType));
// Commit the changes.
scope.Complete();
}
}
}
When I run the code show above I receive an InvalidOperationException:
A property extention cannot edit an item in an Entity Framework namespace
Another possibility that I am evaluating is use ModelTransformExtension class to make changes on the context.CurrentDocument.
You know any way to do this without this exception occurs? Any help or suggestions will be welcomed.
Thanks in advance
Octavio

XML serialization errors when trying to serialize Entity Framework objects

I have entities that I am getting via Entity Framework. I'm using Code-First so they're POCOs. When I try to XML Serialize them using XmlSerializer, I get the following error:
The type
System.Data.Entity.DynamicProxies.Song_C59F4614EED1B7373D79AAB4E7263036C9CF6543274A9D62A9D8494FB01F2127
was not expected. Use the XmlInclude
or SoapInclude attribute to specify
types that are not known statically.
Anybody got any ideas on how to get around this (short of creating a whole new object)?
Just saying POCO doesn't really help (especially in this case since it looks like you're using proxies). Proxies come in handy in a lot of cases but make things like serialization more difficult since the actual object being serialized is not really your object but an instance of a proxy.
This blog post should give you your answer.
http://blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx
Sorry, I know I'm coming at this a bit late (a couple YEARS late), but if you don't need the proxy objects for lazy loading, you can do this:
Configuration.ProxyCreationEnabled = false;
in your Context. Worked like a charm for me. Shiv Kumar actually gives better insight into why, but this at least will get you back to work (again, assuming you don't need the proxies).
Another way that works independent of the database configuration is by doing a deep clone of your object(s).
I use Automapper (https://www.nuget.org/packages/AutoMapper/) for this in my code-first EF project. Here is some sample code that exports a list of an EF objects called 'IonPair':
public bool ExportIonPairs(List<IonPair> ionPairList, string filePath)
{
Mapper.CreateMap<IonPair, IonPair>(); //creates the mapping
var clonedList = Mapper.Map<List<IonPair>>(ionPairList); // deep-clones the list. EF's 'DynamicProxies' are automatically ignored.
var ionPairCollection = new IonPairCollection { IonPairs = clonedList };
var serializer = new XmlSerializer(typeof(IonPairCollection));
try
{
using (var writer = new StreamWriter(filePath))
{
serializer.Serialize(writer, ionPairCollection);
}
}
catch (Exception exception)
{
string message = string.Format(
"Trying to export to the file '{0}' but there was an error. Details: {1}",
filePath, exception.Message);
throw new IOException(message, exception);
}
return true;
}