Entity Framework: Implement interface when generating from database - asp.net-mvc-3

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.

Related

is this a good idea to implement validation in entity framework POCO entities in dabtase first?

It`s seems that the best place to implement validation is as close as possible to the database, so when I use entity framework the nearest objects are the entities, in my case the POCO entities.
The reason for that is that if I want to reuse this POCO entities, the validation is implemented in the POCO objects and then there are less posibilities to insert worng data in the database.
this also avoid that someone try to insert incorrect data in the databse creating another application, or because he does not implement the validation. So it is more secure.
One way to do that is using partial classes that extends the POCO entities and that implements the IValidatableObject interface and return a list of validationresult.
But other way is the following. I have a common assembly that has the following:
One interface that declare the methods that need to implement the repositories.
The POCO entities that will be used by the repositories.
One class with utilities, such as copy entities and methods to validate the data of the entities.
Then I can create many repositories that use different versions of EF or another technology and all of them use the common assembly. This repositories implements the validation using the methods in the common library.
In this case I implement the validation only once. The only problem is that the repositories need to call the methods to validate the data.
But there are advantages in this way, from my point of view. For example, I can validate the data of the entities depending on the type of the operation. For example, if I am adding a new record and the primary key as an autonumeric, if the ID is not 0, then I can throw an exception, or if I try to delete a register when the ID is 0, then I don't need to send the command to the database.
So this second solution solves the problem to implement the validation as close as possible to the database, bacause is used in the repository, that is the element that access to the database, but has the problem that if some developer creates a new repository and not use the validation methods, I can have incorrect data in the database.
So my question is if the best option is to use validation with partial classes or to use a common library and the validation is implemented in the repositories, that is really what the users will use.
Thanks.
OK - phew, big question. My opinion is that the APPLICATION DOMAIN of the application is the boss of everything. The database is just an add-on service. So, the application domain should ultimately validate ALL objects that are being SENT somewhere. No need to validate object coming out of the DB because they were validated going in.
As an example, what if you were creating some object that needed to be sent off to a web service and it needed validation. Lets say it was never going near the database or the repositories. Once the DOMAIN business objects have been validated, they can then be sent for persistence or anywhere else.
Another thing to consider is what you mean by validation. Does it mean the datatypes are correct? Does it mean the business object is valid? Does it mean the business object is valid in the given context? It could mean all or only some of these things.
As an example, what if your system allows users to partially update records (common with very long input forms). The business object may only become valid when ALL the required data is captured, but the database allows persistence of "partial" data. In other words, you can save the business object to the database although it is not valid for further processing yet. etc etc....

LINQ DataContext Object Model, could it be used to manage a changing data structure

I am currently working on a project where we are rewriting software that was originally written in Visual DataFlex and we are changing it to use SQL and rewriting it into a C# client program and a C#/ASP.Net website. The current database for this is really horrible and has just had columns added to table or pipe(|) characters stuck between the cell values when they needed to add new fields. So we have things like a person table with over 200 columns because stuff like 6 lots of (addressline1, addressline2, town, city, country, postcode) columns for storing different addresses (home/postal/accountPostal/ect...).
What we would like to do is restructure the database, but we also need to keep using the current structure so that the original software can still work as well. What I would like to know is would it be possible using Linq to write a DataContext Object Model Class that could sort of interpret the data base structures so that we could continue to use the current database structure, but to the code it could look like we where using the new structure, and then once different modules of the software are rewritten we could change the object model to use the correct data structure???
First of all, since you mention the DataContext I think you're looking at Linq to SQL? I would advice to use the Entity Framework. The Entity Framework has more advanced modeling capabilities that you can use in a scenario as yours. It has the ability to construct for example a type from multiple tables, use inheritance or complex types.
The Entity Framework creates a model for you that consists of three parts.
SSDL which stores how your database looks.
CSDL which stores your model (your objects and the relationships between them)
MSL which tells the Entity Framework how to map from your objects to the database structure.
Using this you can have a legacy database and map this to a Domain Model that's more suited to your needs.
The Entity Framework has the ability to create a starting model from your database (where all tables, columns and associations are mapped) en then you can begin restructuring this model.
These classes are generated as partial so you could extend them by for exampling splitting the database piped fields into separate properties.
Have you also thought about using Views? If possible you could at views to your database that give you a nicer dataschema to work with and then base your model on the views in combination with stored procedures.
Hope this gives you any ideas.

how to use codeigniter database models

I am wondering how the models in code ignitor are suposed to be used.
Lets say I have a couple of tables in menu items database, and I want to query information for each table in different controllers. Do I make different model classes for each of the tables and layout the functions within them?
Thanks!
Models should contain all the functionality for retrieving and inserting data into your database. A controller will load a model:
$this->load->model('model_name');
The controller then fetches any data needed by the view through the abstract functions defined in your model.
It would be best to create a different model for each table although its is not essential.
You should read up about the MVC design pattern, it is used by codeigniter and many other frameworks because it is efficient and allows code reuse. More info about models can be found in the Codeigniter docs:
http://codeigniter.com/user_guide/general/models.html
CodeIgniter is flexible, and leaves this decision up to you. The user's guide does not say one way or the other how you should organize your code.
That said, to keep your code clean and easy to maintain I would recommend an approach where you try to limit each model to dealing with an individual table, or at least a single database entity. You certainly want to avoid having a single model to handle all of your database tables.
For my taste, CodeIgniter is too flexible here - I'd rather call it vague. A CI "model" has no spec, no interface, it can be things as different as:
An entity domain object, where each instance represents basically a record of a table. Sometimes it's an "anemic" domain object, each property maps directly to a DB column, little behaviour and little or no understanding of objects relationships and "graphs" (say, foreign keys in the DB are just integer ids in PHP). Or it can also be a "rich (or true) domain object", with all the business intelligence, and also knows about relations: say instead of $person->getAccountId() (returns int) we have $person->getAccount(); perhaps also knows how to persist itself (and perhaps also the full graph or related object - perhaps some notion of "dirtiness").
A service object, related to objects persistence and/or general DB querying: be a DataMapper, a DAO, etc. In this case we have typically one single instance (singleton) of the object (little or no state), typically one per DB table or per domain class.
When you read, in CI docs or forums, about , say, the Person model you can never know what kind of patter we are dealing with. Worse: frequently it's a ungly mix of those fundamentally different patterns.
This informality/vagueness is not specific to CI, rather to PHP frameworks, in my experience.

how do you generate class for LINQ to SQL?

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.

Creating custom class for every Stored Procedure using linq to SQL?

I'm using stored procedure in LINQ, i know it will generate a class T(procedure name + "Result") for me automatically to store the data.
If the name of stored procedure is spCampus, the generated class will be spCampusResult.
My Question:
when i'm using SP should i create custom class that replicate all the properties ( i'm refering to whatever the .dbml creates when you drag and drop the SP)
in my situation i will be using SP... is that fair to say i will be treating as a class object and pass around from model to controller and to view ?
or i will be better off creating a new custom business object contining all the props from .dbml ?
i havent get any clear cut answer
anybody?
In the designer you can shape the object any way you see fit. You can change the names of the properties you can change the name of the object returned from the sproc if you want to. It is also my understanding that you can change the protection levels on the properties as well. This to me means that you can use the LINQ2SQL generated objects as your DTO's or you business objects because you have the power to shape them as you see fit in the designer and since they are partial classes you can extend their behavior without touching the generated class. Hope this helps.

Resources