How do I implement Business Logic on auto generated entities in Microsoft MVC2? - asp.net-mvc-2

I'm new to MVC and I'm trying to figure out how to implement business logic in the auto generated Entities in an MVC project.
I know that if I create my own Model class I can put [Required] and other attributes on the fields but there doesn't seem to be an option to do that in the .edmx file.
Is there something I'm missing here?
Should I be creating my own classes that use the entities and put the logic in there?
It seems like there should be a way for me to do less work.
Thanks!

This can be achieved by using the buddy-class functionality in .NET implemented specifically for this reason. Once you have created your entities in your .ebmx file you can create partial classes to accompany your entities which define your business rules in a 'buddy class'.
[MetadataType(typeof(ProductMetadata))]
public partial class Product {
internal sealed class ProductMetadata {
[DisplayName("Name")]
[Required]
public string Name { get; set; }
[DispayName("Price")]
[Required, Range(1,10000)]
public decimal Price { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
}
}
In the example above, assume that you already have a "Product" type defined in your object context which has properties for "Name", "Price", and "Description". So long as the buddy class type referenced by the MetadataTypeAttribute has matching property names, the attributes applied to the properties in the buddy class will be applied to the implementation type.
Note: if there are any property names in the buddy class which do not match the implementation type, you will get a runtime error. You only need to create matching properties in the buddy class for the properties you are interested in applying business rules to; all properties are optional.

Related

MVC5 website newbie / Annotations on properties of autogenerated modell

i'm new to mvc 5, and I would like to build an asp.net application to interact with an existing database. I'm using VIsual studio 2013 and Entity Framework 6.
I've generated an ADO.net Entity Data Model from an existing database and I'm currently trying to find out the best way to make data validations, to avoid wrong inputs (let's take as example the field Email from entity Users).
The right way seems to be to use Annotations on partial classes. But i don't know how to add an annotation (on the new partial class that i created for that) if the original property declaration is on the autogenerated file.
The autogenerated class, looks like:
namespace Test.Models
{
...
public partial class Users
{
public string Email { get; set; }
}
...
}
Following the idea behind [this post] (Add data annotations to a class generated by entity framework), i'm trying to make a partial class to write the annotations there, like that:
namespace Test.Models
{
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(UsersMetaData))]
public partial class Users
{
[Someanotations]
public string Email { get; set; }
}
}
But on the partial class, i get:
1) Error on the line of "[MetadataType(typeof(UsersMetadata))]", saying that UsersMetadata could not be found, and
2) Error on the line where "public string email", saying that the property is already declared (which sounds logic for me).
How should i annotate on the new partial class the property that is declared on the autogenerated model?
It is possible to define a Regex to be used on the anotation?
Thanks for your time,
John
You're almost there. UserMetadata is actually another class that you apply the annotations to. I usually put both of these in the same file.
[MetadataType(typeof(UsersMetaData))]
public partial class Users
{
}
class UsersMetaData
{
[Someanotations]
public string Email { get; set; }
}

Entity framework questions about keywords and relationships

I am EF new learner, i have some questions to ask:
1.
I don't understand what does virtual mean in for example one to many, i give an example:
one question can have many options for e.g.
public class Question
{
public int QuestionId { get; set; }
public string Title { get; set; }
public virtual List<Option> Options { get; set; }
}
public class Option
{
public int OptionId { get; set; }
public string OptionText { get; set; }
public virtual Question Question { get; set; }
}
but what does the "2" virtual mean, because if i delete the virtual in this line:
public virtual List<Option> Options { get; set; }, i didn't find any differences, it works well as one to many, so can you explain me very clearly and easily what the 2 virtual mean, if it's override, override what?
2.
I don't know when we should use API fluent, for e.g. the previous one to many ex. without api fluent, it's still a one to many Relationship, so please just tell me when we should use it ? in which occasions for example.
3.
in the API fluent, i know "withmany" and "hasmany" together, they mean "many to many", and what's "withrequired? isoptional? "
I think I can answer following points:
EF define all navigation property virtual, so that EF will at runtime create a new class (dynamic proxy) derived from your Brand class and use it instead. This new dynamically created class contains logic to load navigation property when accessed for the first time. This feature is called lazy loading (or better transparent lazy loading).
See the following link for more detail
Entity Framework 4.1 Virtual Properties
2.When to use fluent API
When working with Code First, you define your model by defining your domain CLR classes. By default, the Entity Framework uses the Code First conventions to map your classes to the database schema. If you use the Code First naming conventions, in most cases you can rely on Code First to set up relationships between your tables based on the foreign keys and navigation properties that you define on the classes. If you do not follow the conventions when defining your classes, or if you want to change the way the conventions work, you can use the fluent API or data annotations to configure your classes so Code First can map the relationships between your tables.
http://msdn.microsoft.com/en-us/data/jj591620.aspx
3.See the following link to know What is .WithRequired and .WithOptional options
What part does the .WithRequired play in an EF Fluent API?

Using generic-based role pattern with EntityFramework 4

Maybe I haven't quite get the whole thing about models. I tought that, it was probably wrong, EF framework could map any kind of class. So I did provide classes with different interfaces, with ToString() methods and so on.
I was thinking of reusable/flexible structure of classes for some kind of public organization.
For example, there are next classes
[Serializable]
public abstract class AbstractRole
{
public String Title { get; set; }
public abstract void ExecuteRole();
public abstract Decimal GetSalary();
// ToString(...) implementations and so on
}
[Serializable]
public class Employee<T> : IComparable<Employee<T>>, IFormattable where T : AbstractRole
{
private Person person;
public T Role { get; set; }
// interfaces implementations...
}
So all I wanted is to get flexibility to change employee's role in time and not to bind to its instance (avoid inheritance).
But later I read that generics are not supported by EF.
What should I do?
In case of entity framework you must provide exact type. Base classes are supported only if whole inheritance tree is mapped as well. Interfaces and generic types are not supported at all.
That means that reusable and flexible architecture is not something which can use EF.

Ria service generated code not support partial class

I'm using Ria service class library. This contains 2 library named RiaClasslibrary RiaClasslibrary.Web.
Riaclasslibrary.Web contains ADO.NET entity data model and named BaseModel. BaseModelcontains tPage class.
My problem is
I'm inserting separated tPage class. This class contains 2 public property. show below
public sealed partial class tPage : EntityObject
{
public List<tPage> Children { get; set; }
public tPage Parent { get; set; }
public Boolean IsSelected { get; set; }
}
After I'm inserting DomainService and building RiaClasslibrary.Web class library. But ria service generated code doesn't contains above properties.
You have a question. Why you separate tPage class. You simply insert those 3 property in Modelbase.Designer code.
My answer is: Database doesn't contain those 3 property and If I'm inserting properties in the code, properties removed after updating Entity Model.
#ebattulga
I don't know if you still have this issue, but I will post the answer because I came to similar issue.
The answer for
After I'm inserting DomainService and
building RiaClasslibrary.Web class
library. But ria service generated
code doesn't contains above
properties.
is quite easy but hard to find.
You can read here in section "Shared Code" http://www.silverlightshow.net/items/WCF-RIA-Services-Part-5-Metadata-and-Shared-Classes.aspx
If you want to see custom properties from partial classes on the Client you have to rename class file name from MyClass.cs to simply MyClass.shared.cs. This will create partial class in the code generated Client side.
HTH
Daniel SkowroĊ„ski

MVC2 Modelbinder for List of derived objects

I want a list of different (derived) object types working with the Default Modelbinder in Asp.net MVC 2.
I have the following ViewModel:
public class ItemFormModel
{
[Required(ErrorMessage = "Required Field")]
public string Name { get; set; }
public string Description { get; set; }
[ScaffoldColumn(true)]
//public List<Core.Object> Objects { get; set; }
public ArrayList Objects { get; set; }
}
And the list contains objects of diffent derived types, e.g.
public class TextObject : Core.Object
{
public string Text { get; set; }
}
public class BoolObject : Core.Object
{
public bool Value { get; set; }
}
It doesn't matter if I use the List or the ArrayList implementation, everything get's nicely scaffolded in the form, but the modelbinder doesn't resolve the derived object type properties for me when posting back to the ActionResult.
What could be a good solution for the Viewmodel structure to get a list of different object types handled? Having an extra list for every object type (e.g. List, List etc.) seems to be not a good solution for me, since this is a lot of overhead both in building the viewmodel and mapping it back to the domain model.
Thinking about the other approach of binding all properties in a custom model binder, how can I make use the data annotations approach here (validating required attributes etc.) without a lot of overhead?
Check out the Derived Type ModelBinder in MvcContrib. This allows you to modelbind to derived types through the process of 'typestamping' - which is handled automatically for you when using the RenderTypedPartial(...) helper. MvcContrib partials maintain binding state across partials so the Name/Id prefixes are properly maintained on a deep object graph. If you use other mechanisms like templates, then you'll need to handle the typestamping yourself. This is explained in the documentation page.
Getting back to your questions and how the derived types are resolved with the ModelBinder, you can register the derived type variations with attributes in a mechanism similar to the WCF KnownTypeAttribute or you can do the registration on startup. Either way, these variations are registered once and held onto for performance considerations.
The model binder also solves this problem in a way that does not interfere with data annotation/validation attributes. They will work as you expect them in any other scenario.