Changing one table in EDMX file affect all actions at project. The schema is not valid - asp.net-mvc-3

We are using VS2010 and MVC 3.
This project was working fine. With over 40 tables in EDMX Model. We change a one table over EDMX file and then nothing work.
All actions (related or not with change) gives this error:
The scheme is not valid. Errors:
The type has no key member. Both RelationshipType as EntityType must
have members with BaseType key or key members. The type has no key
member. Both RelationshipType as EntityType must have members with
BaseType key or key members.
Description: An unhandled exception when running the current Web
request. Check the stack trace for more information about the error
and where it originated in the code.
All tables has a key...
We are restoring a old backup, and working fine... rebuild and then nothing work. !!!
Any idea, thank you in advance...
For example: (this is a piece of Modelo.designer.cs)
public ObjectSet Clientes {
get
{
if ((_Clientes == null))
{
_Clientes = base.CreateObjectSet("Clientes"); // ERROR HERE
}
return _Clientes;
}
}
Same error for all tables in the Model (EDMX). We are rebuild Model.designer.cs using right mouse menu option "execute custom tool"
We deleted old Model, create a new and... the same error.

Change EDMX model and then do update model from database -> refresh -> table

Related

ASP.NET MVC User.Identity.GetUserId() returning wrong GUID

I am calling this method from within a Controller method while logged in as a user, with the standard DefaultMembershipProvider code in MVC5 that comes completely out of the box. Like this:
string LoggedInUsersId = User.Identity.GetUserId();
When debugging, this method call returns a GUID that is completely different to the "Id" field GUID stored in the AspNetUsers table. As I only have one user in this table, I have no idea where this other GUID is coming from?
I thought that the Id field value from the AspNetUsers table would be returned for the currently logged in user when you call User.Identity.GetUserId()?
I am definitely checking the same database/environment and looking at the right place.
Solved!
Thanks to this blog post (see point #2):
https://digitaltoolfactory.net/blog/2013/10/five-things-should-should-know-about-the-new-asp-net-identity-membership-system/
The new MVC5 membership stuff had automatically created a new local database on my laptop called "DefaultConnection" where it had generated and placed all the membership tables and data. So GetUserId() was returning a GUID that lived locally in the AspNetUsers table from that local database which did not exist in my other main database that the application was using! Gah.
So the fix was changing this line inside of IdentityModels.cs:
public ApplicationDbContext() : base("DefaultConnection") { }
to:
public ApplicationDbContext() : base("MyConnectionString") { }
Now it works and everything is saved centrally into my application's main database.

WebAPI + EF5, Entity framework does not recover from a DBUpdateException and requires a full restart of the service

I have two table in my database. Table USER and table USER_ADDRESSES
Table USER has UserID , UserName , HumanName
Table USER_ADDRESSES has UserAddresseID, UserID, Address
The two tables are related through the UserID foreign key.
I am working code first. The POCOs are as one would expect I guess:
Public class User
{
Public guid UserID {get;set;}
Public string UserName {get;set;}
Public string HumanName {get;set;}
}
Public class UserAddress
{
Public guid UserAddressID {get;set;}
Public guid UserID {get;set;}
Public string Address {get;set;}
Public virtual User User {get;set;}
}
If I POST a user, it flows through EF and into the physical database - cool
If I POST a UserAddress with the UserID foreign key properly assigned as the UserID of the above user, the userAddress flows through EF into the physical database - perfect.
Now as I am learning this subject, I like to test scenarios that I know will cause errors… Understanding how something fails often leads to greater understanding (IMHO).
To this end, I repeat the above steps.POST a user, then POST an Address but this time with an empty GUID in the Address.UserID property, something I know will cause SQL server to error on,this time EF gets an error back from the DB and surfaces that error in my controller class as a DbUpdateException, which I then act upon to send back a BadRequest ErrorResponse, this would be fine except now I can post nothing to the DB, If I subsequently try to post new Users EF throws a DbUpdateException on every POST. The only way out of this condition is to Stop debugging the WebAPI project, kill IISExpress and restart everything.
My suspicion is that it is something to do with the tracked entities in dbset.Local it appears this collection is happy to store entities which violate database constraints, and even after the DB has thrown an error EF does not remove the faulted entity from its cache, and I guess that every time I call DataContext.SaveChanges(), EF keeps trying to submit the Faulty address entity that it has in it's bdset.Local property and thus prevents me from submitting anything further to the DB until the whole project is restarted and the various dbset.Local collections are flushed.
Ok I understand that, In my controller class I can prevent some of these issues by evaluating the various properties of the object before submitting them to my repository/UnitOfWork and thus prevent them from getting into dbset.Local in the first place, perhaps there is some decoration I can add to my POCOs such that ModelState.IsValid returns false if UserID == Guid.Empty in the UserAddress Entity??? . But surely EF should be able to recover from DB originated errors, such that if an INSERT statement fails when run against SQL server, EF should remove the faulting Entity from its Local cache of tracked objects. Thus preventing the whole system from requiring a complete restart. The upshot of this is that if I had unique constraints on other non key fields, before I attempt to submit an entity I will have to query the DB to ensure that there are no records in the DB which would result in a DBUdateException from being thrown, that approach seems inefficient to me. I would rather take the error and throw it back to the client for them to consider.
Now perhaps it's my responsibility that on the occurrence of a DbUpdateException to do something to remove the faulted entity from the dbset.Local collection or similar. If that's the case how should I go about this?
As I have been writing this I am left wondering: Should EF not be able to recover from DBUdateExceptions in and of its self!? Without the need for an IIS restart. Or should I build my DB with no constraints what so ever and allow clients to put any old rubbish in there. It's my believe that EF Entity tracking should honour db constraints and prevent faulted entities from getting into the dbset in the first place.
Please guide me on the correct way to recover from a DBUpdateException?

The data reader is incompatible with the specified... A member of the type, 'Finalised', does not have a corresponding column in the data reader

I have added a column in my Sql Server Db then in VS i updated model from database, there a template auto generated some code.
The code compiled fine, but when i try access a the data base, the following error occurs:
The data reader is incompatible with the specified
'CompassModel.tbSalesContract'. A member of the type, 'Finalised',
does not have a corresponding column in the data reader with the same
name.
Finalised is the new column i added to my database.
Does anyone know how to track this down, and if so, is there a fix or methodology to follow to avoid in the future?
If you are using a SP then update the newly added column in that Or If you are using inline query put the exact name of the newly added column . The template you are talking about does not contain the newly added column name ..Try to edit the template ..the issue will be resolved.
If you are using a SP, then please make sure the alias names used.. ie. for eg: It should be written as
fieldname as 'aliasname'
thanks,
criss thomas
Hopefully this helps someone out but when I received this error I was trying to return an entity type from a stored procedure.
To fix this I had to add the correct function import mapping. In your edmx go to the Model Browser view and navigate to Funtion Imports. Right click your sproc name and select function import mapping. There you can map your sproc return results to the appropriate entity property.

Changed existing entity model and manually updated SQL Server database but still get context changed error

I have an existing MVC3 application and database that is on a SQL Server 2008 R2 and I had to add a bool item to an existing model.
After I added it to the model, I rebuilt and published the project. Then I opened up SQL Server Management Studio and went to the table and added the entry to the column as a bit, I had to make it nullable since the table already contains data.
I thought this would be all that I would need to do to get everything working. However I got this error:
The model backing the 'psllc_DB' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.
I'm not sure what else to do, I went back to the code and changed the bool to bool? so it will be nullable but this didn't help either. I can't drop the entire database since it's full of data, however as a last ditch possibility I could drop this table and re-create it cause it only has a few entries, but I don't know if that will work. I'm not sure what else to do so any advice would be very appreciated.
Update
Since I'm not getting any responses, let me rephrase my question.
How should I update my database (a SQL Express mdf file) to add a bool Column to a Table that has data already? I need the database to match my updated MVC 3 Entity Code First model otherwise I get the above error.
Thanks
Since this is code-first, you should do this code-first: change the class and use EF-migrations to change the database. The way you do it, the model and the database may match, but the meta information in the database is not updated.
By the way, if you supply a default value, you can add a non-nullable column.

MVC3 - Error setting up Controller with Entity framework

The steps I go through...
Add new ADO.NET Entity Data Model > Generate from DB > Setup new connection string to adventureworks db > Next > Select table "DatabaseLog" > Finish. Verify DatabaseLog is visible in the edmx view.
Right click controller > Add controller
TemplateController with read/write actions and views, using Entity
Model class
AdventureWorksDWEntities
Context
New data Context > Accept default name
View
Razor
Click Add.
Produce Error:
"Unable to retrieve metadata for 'DatabaseDocumentor.models.AdventureWorksDWEntities'.
System.Data.Edm.EdmEntityeType: EntityType 'AdventureWorksDWEntities' has no key defined. Define the key for this entitytype.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet 'AdventureWorksDWEntities' is based on type 'AdventureWorksDWEntities' that has no keys defined.
I tried again using AdventureWorks (not AdventureWorksDW) and this time it worked. But, I still don't understand what to pick when generating a controller. I have 3 options:
Template
Here I picked Controller with read/write actions and views, using Entity. This is easy enough to understand. I want to have my tables generated for me so I pick this option.
Model
This is what I want to model. In this case I want to model the "Department" table. So I choose Department.
Context
This one is real fuzzy to me. I chose *Name*Entities. This is the value in the web.config connection strings area. Why do I need to choose my connection string as the context? I only know context as "an object that I use to get to my entities" in C#. So, here it's hard for me to visualize. Do I need to always choose my connection string for the context?
This issue can occur when the Context is not correctly chosen from the dropdown. The context should be the value stored in the web.config
<add name="NamedEntitiesCs1"
that also contains the Model you want to generate.
I found what the issue is...
I have a 3 tiered architiecture I'm using with each of the below projects in one solution.
1.YeagerTech
2.YeagerTechWcfService
3.YeagerTechModel
No matter what, even though my wcf service references my model, the startup project (1) is not "smart" enough to recognize the metadata to create the Controller. In this case, you must include a reference to your project that includes your edmx model.
You must also ensure that the connectionstring also resides in the startup project (1) via the web.config file, in order to get the connection for the metadata.
I found the answer, the model class should have a key, that is an ID property i.e
public int ID { get; set;}
save the changes and the build or rebuild the solution.
That should be able to work out.
your property in your Model for the ID must be declared as public. rebuild and try again, it should work

Resources