I have a linq-to-sql class. I have a property "Password" for which I want to call the underlying ASP.NET Membership provider. Thus, I do not want this property written out directly but via my own code. I basically want to create a facade/proxy for this property such that I may use the underlying membership provider or a custom stored procedure.
I want to accomplish without modifying the LINQ-TO-SQL designer generated code, if at all possible.
It is possible. You can add your properties and methods to linq generated class using partial class mechanism. Linq generated classes are marked partial so you can add class members with:
public partial class YourLinqClass
{
// your methods and properties. refer linq properites and methods with "this."
// example:
public string Password
{
get
{
int id = this.UserId;
string password = // ... get password
return password;
}
set
{
// ...
}
}
}
You have to place the partial class in the same namespace as the rest of dbml.
The best option is to remove the property from the designer and write it in code, in the partial class, as described by PanJanek.
However, if you do it this way, you are pursuing a bad design. You're introducing a dependency into your entity class that breaks layer encapsulation. Entity classes shouldn't know about providers any more than they know about the DataContext that loads them. They aren't really meant to be anything more than containers for data going in and out of the database.
You should consider making a separate class that wraps the entity, the context, the username provider, and whatever other services you require, and in that class retrieve the username and do the required operations to your entity.
It looks like it might be possible to create a custom DataContext to handle this situation.
http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx
There are partial methods for the individual properties as, well and an OnValidate method.
In my case, I think the best solution is to throw an exception in the property changing method and add a public method for setting this individual property. This solution while not perfect will avoid touching the SQL generated code, where the property could be set to readonly or the setter removed.
Other suggestions welcome.
Related
I am very new to DDD and reading various discussions on validation (where to put it) on the stackoverflow as well as on the web. I do like the idea of keeping the validations outside the entities and validate them depending upon the context. In our project, we have an entity called MedicalRecord and there are various rules for when one can be created or can be saved. I want to create a service layer, let's say RecordService, that would do some check to make sure if a user can create a medical record before creating one. I also want to create MedicalRecordRepository that would save the medical record. What confuses me is the access modifies on my entity and repository classes. Since both will be public, how can I enforce the client of my application to use the service instead of just creating new medical record (with public constructor) and use the repository to save it? I am using c#. I know DDD is language independent but wondering if someone could provide some thoughts on this.
Thanks.
You must control record creation by making the c'tor non-public and allowing creation only through a factory:
public class MedicalRecord
{
internal MedicalRecord()
{
}
}
public static class MedicalRecordFactory
{
public static MedicalRecord Create(User onBehalfOf)
{
// do logic here
return new MedicalRecord();
}
}
For the internal keyword to be applicable, either both classes must be in the same assembly or the class assembly must allow the factory assembly access with the InternalsVisibleTo attribute.
Edit
If you need to be able to perform validation at any time, you additionally have to encapsulate validation logic in another class (here partially done via an extension method):
public static class MedicalRecordValidator
{
public static bool IsValid(this MedicalRecord medicalRecord, <context>)
{
return IsValid(<context>);
}
public static bool IsValidForCreation(User onBehalfOf)
{
return IsValid(null, onBehalfOf);
}
private static bool IsValid(<context> context, User user = null)
{
// do validation logic here
}
}
then, the factory could do this:
public static MedicalRecord Create(User onBehalfOf)
{
return IsValidForCreation(onBehalfOf) ? new MedicalRecord() : null;
}
and you could also always do this:
if (myMedicalRecord.IsValid(<context>))
{
// ....
Only use your repository to retrieve your entities; not to save them. Saving (persisting) your entities is the responsibility of your unit of work.
You let your service change one or more entities (for instance a MedicalRecord) and track the changes in a unit of work. Before committing the changes in your unit of work, you can validate all entities for validation needs across entities. Then you commit your unit of work (in a single transaction), which will persist all your changes, or none at all.
For clarity, your MedicalRecord should protect its own invariants; such that a client retrieving a MedicalRecord using a repository, calling some methods to modify it and then persisting it using a unit of work, should result in a "valid" system state. If there are situations where this is not the case, then it can be argued that it should not be possible to retrieve a MedicalRecord on its own - it is part of some larger concept.
For creation purposes, using a factory like #Thomas suggests below is a good approach, although I think I'd call it a service (because of the collaboration between entities) instead of a factory. What I like about Thomas' approach is that it does not allow a client to create a MedicalRecord without a User (or other contextual information), without tying the MedicalRecord tightly to the user.
I have recently been learning MVC3 using Entity Framework 4.3 and Dependancy Injection so I can implement unit tests at a later date. I am now trying to implement some functions I have seen in various examples however I have hit a few issues that seem to stem from my use of dependancy injection and therefore I would like someone to point out where I am going wrong.
My first question is pretty simple; In most MVC3 examples I have seen, the access to the database is done in controllers, but when using dependancy injection I seem to need to refactor this code out to the implemented repository. Is this normal and correct?
My second more indepth issue is dealing with this simple example:
I have this method in my repository class which is pretty much copied from an online example (here). However I get an error regarding the Include part, and the intellisense does say that the variable needs to be a string. I have tried the original code from the link I mentioned earlier and that works fine, the only major difference between the project is that I am using dependancy injection.
public ExampleUser GetStruContractUser(int id)
{
ExampleUser user = context.ExampleUsers
.Include(i => i.ExampleRoles)
.Where(i => i.UserID == id)
.Single();
return user;
}
Changing the Include parameter to the following works fine.
public ExampleUser GetStruContractUser(int id)
{
ExampleUser user = context.ExampleUsers
.Include("ExampleRoles")
.Where(i => i.UserID == id)
.Single();
return user;
}
For reference this is my DbContext class that I am using:
public class EFDbContext : DbContext
{
public DbSet<ExampleUser> ExampleUsers { get; set; }
public DbSet<ExampleRole> ExampleRoles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<ExampleUser>().ToTable("User", "MySchema");
modelBuilder.Entity<ExampleRole>().ToTable("Role", "MySchema");
modelBuilder.Entity<ExampleUser>()
.HasMany(m => m.ExampleRoles)
.WithMany(t => t.ExampleUsers)
.Map(a =>
{
a.MapLeftKey("UserID"); // your PK column name in user table
a.MapRightKey("RoleID"); // your PK column name in role table
a.ToTable("UserRole", "MySchema"); // your join table name
});
}
}
Is this an issue due to my use of dependancy injection or is there something else going on that I am misunderstanding?
If you need more information, please ask and I will try and provide it.
Thanks very much.
Question 1:
Using DI doesn't force you to use a repository pattern, in fact they are not related. It's just a nice way to avoid tightly coupling your controller classes to the database context class, and being able to thus test those classes more easily. Repository gives you the ability to hide the implementation details of how you're accessing the DB, and allows you to switch ORM:s if that were to happen (and it never ever does). Repository relies on you to provide interfaces for your DbContext, and so does using DI.
What you want to do is use your DB through an interface nevertheless, and seeing as you're using DI, you could just inject the reference to the DbContext class in the constructor of your controllers, and let the DI controller do the work for you.
The reason it is preferable to pass in an interface that defines the repository to the Controller over passing an interface that defines your DbContext, is because making an interface of the latter can easily become overly complex, whereas sticking to a repository is much simpler. For simplicity though, I'd start with just using DbContext directly, and then expanding from there.
Question 2:
Include needs to contain the name of the table as a string. So your latter use of Include is correct, and the former isn't.
If I remember correctly, you can do this tho: ".Include(i => i.ExampleRoles.Name)" to achieve the same thing.
Yes, extracting your database layer (repositories / context) and then injecting it into your business layer (controllers) is very normal and a good way future proof your application. What if you ever wanted to change your database ORM from Entity Framework to something else? Having it tightly coupled with your controllers would create a huge headache.
Your second issue, with include, is unrelated to the dependancy injection.
Include on a dbset using lambdas an extension in System.Data.Entity. You'll need to include that reference if you want to use it.
I'm working on an MVC3 project I have created my database on SQL server 2008 then I add it using entity data model, now I have the .edmx I don't want to generate the code of the classes because till now it's not stable and I don't feel the need to do that except to make the validations
I'm wondering if there is a way to make validation directly using the .edmx without generating the code of classes
Need server and client side validation
Cheers
You can't do it from edmx. You can however have classes that add the metadata to the edmx generated classes.
This adds a metadata containing class to the class that was generated by the edmx:
[MetadataTypeAttribute(typeof(CustomerMetadata))]
public partial class Customer
{
}
and then you have the metadata class which has the metadata attributes:
internal sealed class CustomerMetadata
{
public int ID;
[Required]
[StringLength(60)]
public string Name;
}
Edit:
EF generates all it's classes as partial. That means you can add functionality in a different file to the same class. We use this feature to add an attribute telling .net that there's a class that has the metadata information. In this case the class with the metadata for the Customer class is CustomerMetadata.
It has all the properties that you want decorated with metadata. In this case ID is not actually required to be there.
(I would have added this as a comment but I don't have enough reputation points yet)
Be sure that the namespace in your partial class exactly matches the EF-generated class's namespace, including the correct case.
I am using the database first approach with entity framework, when i used to work on the default template the database tables were mapped using the ObjectContext, so i used to create #partial classes & [MetadataType(typeof ) to apply the data annotation ,, but when i start using the Dbcontext code generation template to map the database tables i found that it will create .tt folder in my Model area were i find that i can apply the data annotation directly to the .cs classes themselves without the need to create partial classes as in objectcontext case.
Currently the data annotations are working fine,, but would my approach cause me problems i am not aware of and i should create partial classes as i used to do with the Objectcontext ?
BR
In general, you shouldn't edit generated code because changes you make will be overwritten on re-generation. This is why most generators emit partial classes.
The best practice for your situation would be to create a new file in your solution with another partial class declaration. In that file, add the MetadataType attribute to the class, and add your property-level validation attributes to the "buddy" class (the one referenced in the attribute). This allows you to use validation attributes on the generated properties and, should your model/database change, you can still re-generate your model classes without losing them.
For example, your new file might look something like:
[MetadataType(typeof(PersonMetadata))]
partial class Person
{
// Add logic to the generated class in here.
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
class PersonMetadata
{
// Add attributes to the generated properties in here.
[Required]
public string FirstName { get; set; }
}
Create the same partial classes to define your metadata OR you can simply reverse engineer your existing database using the Entity Framework Power Tools so you have POCO classes. Then you can use the fluent API (you'll see the validations it adds for you) instead of data annotations to give you server side validation.
If you want client side, then you can still apply them to your models, as they wont be regenerated every time you compile .
however - I would recommend you create ViewModels and use AutoMapper to map between your EF objects and viewmodels. Then you can apply your annotations directly to your ViewModels.
My understanding of your situation is that you reverse-engineered your Database-First style to a Code-First style. If your context class inherits from DbContext, you are in Code-First style now (unless there is some strange hybrid possible, which I don't know about!).
In code-first, there is really no point of creating partial classes for data annotations, IMO.
I have several thoroughly unit-tested and finely crafted rich DDD model classes, with final immutable invariants and integrity checks. Object's instantiation happens through adequate constructors, static factory methods and even via Builders.
Now, I have to provide a Spring MVC form to create new instances of some classes.
It seems to me (I'm not an expert) that I have to provide empty constructor and attribute's setters for all form's backing classes I want to bind.
So, what should I do ?
Create anemic objects dedicated to form backing and transfer the informations to my domain model (so much for the DRY principle...) calling the appropriate methods / builder ?
Or is there a mecanisms that I missed that can save my day ? :)
Thank you in advance for your wisdom !
The objects that are used for binding with the presentation layers are normally called view models and they are DTOs purposed toward displaying data mapped from domain objects and then mapping user input back to domain objects. View models typically look very similar to the domain objects they represent however there are some important differences:
Data from the domain objects may be flattened or otherwise transformed to fit the requirements of a given view. Having the mapping be in plain objects is easier to manage than mappings in the presentation framework, such as MVC. It is easier to debug and detect errors.
A given view may require data from multiple domain objects - there may not be a single domain object that fits requirements of a view. A view model can be populated by multiple domain objects.
A view model is normally designed with a specific presentation framework in mind and as such may utilize framework specific attributes for binding and client side validation. As you stated, a typical requirement is for a parameterless constructor, which is fine for a view model. Again, it is much easier to test and manage a view model than some sort of complex mapping mechanism.
View models appear to violate the DRY principle, however after a closer look the responsibility of the view model is different, so with the single responsibility principle in mind it is appropriate to have two classes. Also, take a look at this article discussing the fallacy of reuse often lead by the DRY principle.
Furthermore, view models are indeed anemic, though they may have a constructor accepting a domain object as a parameter and a method for creating and updating a domain object using the values in the view model as input. From experience I find that it is a good practice to create a view model class for every domain entity that is going to be rendered by the presentation layer. It is easier to manage the double class hierarchy of domain objects and view models than it is to manage complex mapping mechanisms.
Note also, there are libraries that attempt to simplify the mapping between view models and domain objects, for example AutoMapper for the .NET Framework.
Yes you will need to create Objects for the form to take all the input, and the update the your model with this objects in one operation.
But I wont call this objects anemic (especially if you do DDD). This objects represent one unit of work. So this are Domain Concepts too!
I solved this by creating a DTO Interface:
public interface DTO<T> {
T getDomainObject();
void loadFromDomainObject(T domainObject);
}
public class PersonDTO implements DTO<Person> {
private String firstName;
private String lastName;
public PersonDTO() {
super();
}
// setters, getters ...
#Override
public Person getDomainObject() {
return new Person(firstName, lastName);
}
#Override
public void loadFromDomainObject(Person person) {
this.firstName = person.getFirstName();
this.lastName = person.getLastName();
}
// validation methods, view formatting methods, etc
}
This also stops view validation and formatting stuff from leaking into the domain model. I really dislike having Spring specific (or other framework specific) annotations (#Value, etc) and javax.validation annotations in my domain objects.