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
Related
I'm having a few tables on SQL Server, which have similar structure - int Id and string Value.
This tables linked to main table via foreign key, so I'm wrote a bit of logic for mapping a string values to id's in models in MVC Razor. This feature requires that models used as dictionary implement simple IKeyValue interface with Id and Value, but after updating model from database I can loose interface implementation from models and must write it again.
Any way to automate this?
Are you modifying the auto-generated file? If so, you should not do this, for the exact reason you describe in your question -- it will get overwritten.
All of the classes in the generated file should be partial. You can take advantage of this by creating another class (in a different file, but in the same project), make sure it has the same declaration (and namespace), and have it implement the interface. This way the class will implement the interface, but will not be overwritten the next time you refresh the schema from the database.
I'm currently wrapping my head around some problem with Core Data.
I have one user model in its own store that I do not have any control over, as it gets shipped with a framework. A Persistent Store Coordinator, Managed Object Model and Context for this model gets created automatically and cannot be touched. In it, this model has a single user entity
On the other hand, I have a properties model with a properties entity in it that I have complete control over. In there I store properties for some user entities in the other store. Both user and property entities have an id attribute similar to a foreign key.
This model has it's own Persistent Store Cordinator, Managed Object Model and Context.
What I now want is to have the associated user entity as an attribute of the properties entity so I might be able to bind to key-paths similar to myproperty.user.someValueOfTheUserEntity (I'm aware that myproperty might be an array when using fetched properties).
However, as cross-store relationships are not supported I thought of using a weak relationship via Fetched Properties. That one would just have to match the two corresponding id attributes. I have created a Fetched Property for the user in Xcode and the required accessors in my properties entity's class file (As suggested in other questions, I'm treating the values returned by the Fetched Property as an array).
However, I'm unable to set a destination entity for the Fetched Property in Xcode, as the target entity resides in a completely different store. Would I also have to define my user entity in the properties store? If so, how does Core Data know that that entity shall be fetched not from my properties store but from the users store?
Some threads mentioned using configurations for this, but I cannot find any documentation that goes further than mentioning "use configurations for this".
Can somebody enlighten me on how to set up cross-storage fetched properties? #
You can use several persistent stores that share the same data model:
Use single data model (xcdatamodeld) and add all your entities
Create configurations (Editor/Add Configuration) for each "logical set" of
entities that should be stored in separate store file
Assign (Drag) entities to appropriate configurations
Add configured persistent stores to your context (see below)
Configure fetched properties
// 1. Add "static", read-only store
[coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:#"your static configuration name goes here..."
URL:storeUrl
options:#{
NSReadOnlyPersistentStoreOption: #(YES),
NSInferMappingModelAutomaticallyOption : #(YES)
}
error:&error];
// 2. Add "dynamic", writable content
[coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:#"your dynamic configuration name goes here..."
URL:storeUrl
options:#{
NSMigratePersistentStoresAutomaticallyOption: #(YES),
NSInferMappingModelAutomaticallyOption : #(YES)
}
error:&error];
Am new to ASP.NET MVC 3.0. Request expert's view on the below mentioned scenario.
I have a customer details page, where only Name is editable. There are 10 other customer properties that are non editable and displayed using SPAN. When user submits the page, I need to update only the Name.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
Anyone tried caching model (or viewmodel) using session id? Is it a good practice?
You are almost thinking in right direction.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
In Update Method **Load Customer again and update name Only as required and then save
**For 2 reasons
The first and most important rule is 'don't trust user data'. and
Concurrency and to avoid saving old data. See this example
Instead of using Session, I will suggest to use Hidden Field for record LastUpdateDateTime and Customer ID which will be posted back in the model to retrieve record and verify LastUpdatedtime with database record
Tipically, you should use a view model different than the database model. Having said that,in your current case the situation is very simple, submit only the name to the controller and then set the Name property of the object you get from EF with the submitted name.
Caching the view model or the model isn't your concern. The database model caching is handled by EF, your problem is mainly a lack of clear application layering. IN fact I strongly suggest to learn a bit more about the MVC pattern, basic application architecture (2-3 layering) and when and how to use a OR\M (which EF is).
use hidden inputs for other properties in your form. In that way you can get all properties binded to your EF entity and you dont need to get entity again from db.
#Html.DisplayFor(model=>model.x)
#Html.HiddenFor(model=>model.x)
or you can serialize the entity(if you use POCO entities) and set to hidden input. When you post back you should deserialize the entity.
My choice is always first one. :)
I have created a web site using mvc 3 and Ef code first , now after publishing the site and it's DB I have found out that I need to add a new columns to one of my DB table,
(the DB already has a lot of data in it )
should I add the columns direct to the DB or should I add to the class?
(just a simple string with get and set)
And how can I do it without losing my data in the DB ?
thanks
Adding the columns to the class should be enough. Evidence you can find here.
Here is the full list of changes that migrations can take care of automatically:
Adding a property or class
Nullable columns will be assigned a value of null for any existing rows of data
Non-Nullable columns will be assigned the CLR default for the given data type for any existing rows of data
Renaming a property or class
See ‘Renaming Properties & Classes’ for the additional steps required here
Renaming an underlying column/table without renaming the property/class
(Using data annotations or the fluent API)
Migrations can automatically detect these renames without additional input
Removing a property
See ‘Automatic Migrations with Data Loss’ section for more information
I suggest you to add the columns direct to the DB and to the class, and test it on the local machine.
I am using linq to sql for my mvc 3 project. There are several ways to generate domain modal class files.
sqlmetal
Object Relational Designer
hand code
I always hand code those model class files. because files generated by sqlmetal or designer are messy. whats your opinion? whats the best way to do it.
EDIT:
I am using MVC 3, not 2. Maybe I am wrong, but this is how I validate. I gonna end up writing all those class files anyway, so whats the point to use tools to generate them???
public class User
{
[Required]
public string Password { get; set; }
[Required, Compare("Password")]
public string ComparePassword { get; set; }
}
We have hundreds of tables across multiple databases (one server). We do table first development, drag the tables onto different DBML designer files each in different folders representing different namespaces within each project. The designer files are marked not to compile, and we use a custom built T4 template that generates our code by reading from whatever DBML files are in the project. This lets us have full control of the code that's generated, so we can do things like implement an interface (IAuditable is one example where we have CreatedBy, CreatedDate, ModifiedBy, ModifiedDate). We can also put System.ComponentModel.DataAnnotations on our Linqed objects this way too without resorting to Buddy Classes. We have a second T4 template that's in charge of refreshing the DBML from the database, so we can ensure that tables have the 3 part prefix (db.schema.tbl) and so we don't have to delete and re-add to the designer. The XML just gets changed based on reading the db schema and updating the DBML. We also generate a repository/manager object for each POCO that have a few common query operations like GetByID(), and also handle commits and the audit logging. These managers get extended with all the custom queries you'd need to write against each table, and they own the DataContext. This design is sometimes known as the "Mommy-may-I?" approach, where the object Linqed to the table has to ask its manager to do everything for it.
I've found this to be a very versatile and slick way of doing L2S, and it's made our back-end development a breeze so that we can put our focus on the user experience. The only downside is that if we do associations across namespaces, you have to manually add those to the partial class yourself, because otherwise you'd have to add that foreign table to another DBML in order to draw the association. This is actually not such a bad thing as causes us to really think about the specificity of our namespaces and cut down extra ones. Using T4 this way is a great way to develop DRY (don't repeat yourself). The table definition is the only place you need to change the structure and it all propogates. Validation goes in one place, the POCO. Queries go in one place, the manager. If you want to do something similar, here's a good place to start.
Even tho the Designer generated classes are messy, what does it matter to you?
There's, I dare say, absolutely no need to ever open one of the design files.
If you need to extend any of the entities defined in your model, they are all partial classes so you can just create your own partial class of the same name and implement your stuff...
When I do use L2S, I just use the designer.