Entity Framework 4 - is it good to add a custom field? - c#

I create a desktop application using C# + EF 4.0. I'm aware that it's normal to add a custom method to Entity Framework EntityObject using partial classes:
public partial class EntityModel: EntityObject{
public void MyMethod() { ... }
}
But I need to add a custom field to store an information that I don't want to hold in database.
So would it be normal or is there any way to do it?

Sure, just add the property you need like:
public string MyCustomField { get; set; }
But bear in mind that it's stateful for that object so it's not going to persist anywhere unless you do that yourself and it's going to hold a different value for each object, unless of course you made it static, but I would strongly recommend against that.

As long as it's related to the class and doesn't really belong somewhere else, then it's completely normal.

Related

C# to use static class to create collection of the class or to use collection class

I have a design problem,
Basically, I have a class called Currency
public class Currency
{
public int ID;
public string Name;
public int RoundingValue;
public Currency() { }
public void GetData() { // Some SQL query code // }
}
Sometimes it is necessary to fetch all the currencies that there are in the system to make a decision concering exchange rates, compatability of payment, etc.
I see two ways of doing that (fetching data):
1) To make a static method inside Currency class to do it. That involves creating SQL connection instance inside it(not sure if that is the right thing to do), creating List<Currency> instance to store the collection, and then pass it outside the class.
2) Create collection of the class via extending Collections.BaseCollection class, make instance of it, doing the same SQL query, and then return the result. But that class will provide no additional functionality, and probably won't ever (the same for Currency itself.
In other cases, I used extended collections, because they needed to store additional info, based on the contents of the collection.
But in this case, no additional info is created or functionality provided.
So, what design would be more practical?
If there is an alternative to the these solutions, I would be more than happy to hear it.
I would suggest simply populating a List<Currency> then returning it as IList<Currency>. That way if you change it in future to use a custom collection, you won't break any consumers.

Inheritance in .Net EntityFramework 4.0 for similar database tables

I am looking for a solution in the following problem:
I have many tables that differentiate from one another in few/none columns (Why this happens is not the case as I have not designed said database nor can I change it).
Example:
Table User: Columns{name,surname,age}
Table OldUser: Columns(name,surname,age,lastDateSeen}
etc
Is there any way to indicate to the EntityFramework 4.0 in Visual Studio to extend a base class consisting of _name,_surname,_age fields and their corresponding properties so that I can use that class for batch jobs in the code?
My current solution is to make this class and use converters to pass the values from the persistent objects its' objects. It works but it is not elegant and I don't like it.
I come from a java/hibernate environment where this is basic functionality.
(for future refernce can the same thing be done if I want the classes to implement an interface?)
Thanks in advance.
Since your RDBMS (at least SQL Server 2008 and older) doesn't allow for table inheritance, I would recommend that you do not use inheritance in the DB model in C#. This is especially recommended when you cannot control the design of the tables.
Instead use an interface if you actually have clients of those classes who will benefit from the abstraction, but not being able to control the design of the DB makes this less valuable because the DB designer could change the tables thereby making your EF classes no longer implement the interface:
public interface IUser {
public string Name { get; }
// etc...
}
public class User : IUser {
public string Name { get; set; }
// etc...
}
public class OldUser : IUser {
public string Name { get; set; }
// rest of IUser
public DateTime? LastSeenOn { get; set; }
}

Generic Windows Form Template

I am creating a generic Windows Form that accepts T and uses reflection with custom attributes to create labels and input controls at run-time.
Example:
class GenericForm<T>: Form where T : ICloneable<T>
{
}
Here's a link to a previous question for the form code: SO Question.
This form could accept the following entity class as an example:
class Vehicle: ICloneable<Vehicle>
{
public int Id { get; set; }
public int Name { get; set; }
public int Description { get; set; }
}
As you could imagine, the magic behind the form would use reflection to determine data types, validation criteria, preferred control types to use, etc.
Rather than re-inventing the wheel, I thought it would be worth asking on SO if anyone knows of such frameworks. Needless to say, I'm looking for something simple rather than a bulky framework.
eXpressApp Framework (XAF) can generate UI on the fly. In a simple case, a programmer will create business entities only, and will not care of UI at all.
As far as I know, there are no frameworks that generate the UI code at runtime. There are plenty of tools (code-generators) that do this before. But you wouldn't have the advantage of "only" changing the code - you'd had an extra step where you would need to start the code generator.
If you really want to create the UI information at runtime - I'd generate Attributes for your properties, that would tell your UI generator how to deal with this property (if no Attribute is given - have a default for your datatypes). It's a lot of coding but could save you time for small to medium projects in the future.
Another thing you could do is to externalize your UI information into an XML file and have a generator for that one. There's actually a framework that does that - have a look at the re-motion framework. I don't know if the part of the UI is free but it has some functionality (i.e. mixins) that could help you fulfilling your task.

How to create custom get and set methods for Linq2SQL object

I have some objects which have been created automatically by linq2SQL.
I would like to write some code which should be run whenever the properties on these objects are read or changed.
Can I use typical get { //code } and set {//code } in my partial class file to add this functionality? Currently I get an error about this member already being defined.
This all makes sense.
Is it correct that I will have to create a method to function as the entry point for this functionality, as I cannot redefine the get and set methods for this property.
I was hoping to just update the get and set, as this would mean I wouldn't have to change all the reference points in my app. But I think I may just have to update it everywhere.
Not sure about read, but you could track changes of your objects. E.g. there is PropertyChangedEventHandler on auto generated entities.
So what have you do is to white a partial class (let's assuming you have a Person entity):
public partial class Person
{
public Person()
{
this.PropertyChanged +=
new PropertyChangedEventHandler(Person_PropertyChanged);
}
protected void Person_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// your code here
}
}
What I did when I wanted to do this was make the property private/inaccessible (since this can be done as part of the DBML definition without editing the generated code), and give it a different name than the property I want to expose. Then I implemented a public wrapper property in a partial class, using the name I wanted to expose. Then (if you want to be really fancy) implement a LINQ provider that can convert queries that refer to the wrapper properties to queries that refer to the underlying properties. I have done all this and it's been working well, but the custom LINQ provider was tricky.
Unless you modify the generated code that was made, and then add additional code to the setter (such as using the pattern like in WPF, with INotifyPropertyChanged), then this would be impossible.

Should one extend or encapsulate ORM objects?

I'm having trouble understanding how to use ORM generated objects. We're using LLBLGen for mapping our database model to objects. These objects we encapsulate in another layer which represents our business model(I think).
Maybe this bit of code will explain this better.
public class Book { // The class as used in our application
private BookEntity book; // LLBLGen entity
private BookType bookType; // BookType is another class that wraps an entity
public Book(int Id) {
book = new BookEntity(Id);
}
public BookType BookType {
get { return this.bookType; }
set {
this.bookType = value;
this.book.BookType = new BookTypeEntity(value.ID);
this.book.Save();
}
}
public int CountPages() { } // Example business method
}
Exposing the entity's fields like properties feels awkward, since I'm mapping all over again. With list-types it's even much worse, since I have to write a "Add" and "Remove" method plus a property that exposes List.
In the above example in the BookType setter I need access to the BookTypeEntity object, I can get this object by instantiating a new one using the ID oh the BookType object. This also doesn't feel good.
I'm wondering if I shouldn't just extend the BookEntity object and add my business logic there? Or maybe use partials?
In the LLGLGen examples they use the entity objects directly, but this looks very messy to me. I want to have objects which can also have methods for my business logic(like CountPages) in the code above.
I've never used LLBLGen for mapping, but most of the ORM tools I've worked with generate partial classes. I then add any custom code/logic I'd like to add to those objects in a seperate file (so they don't get over-written if the partial classes are re-generated).
Seems to work pretty well. If you don't get partial classes from your ORM, I'd create a Facade which wraps your Data Object with your Business Logic...that way the two are seperated and you can re-gen one without overwriting the other.
UPDATE
Partial classes support implementing an Interface in one declaration of a partial class and not the other. If you want to implement an interface, you can implement it in your custom code partial file.
Straight from MSDN:
partial class Earth : Planet, IRotate { }
partial class Earth : IRevolve { }
is equivilant to
class Earth : Planet, IRotate, IRevolve { }
Dunno if it's possible in LLGLGen, but what I generally do when working with ORMs is to create an interface to the persisted class, in your example IBook. I expose this interface via a public getter from the wrapping class. This way, if needs will be, you can extend you IBook the way you want if you need to add some custom behaviour to its fields.
Generally speaking, I think there's 3 ways of "mapping" your ORM-entities to your domain:
The way you've posted. Basically, remap everything again
The way I posted, expose the ORM-entity as an interface
Expose the ORM-entity directly
I don't like #1, cause I don't like to have 2 mappings in my application. DRY, KISS and YAGNI are all violated by this.
I don't like #3 cause it would make whatever consumer-layer of your domain-layer talk directly to the ORM layer.
.. So, I go with #2, as it seems to be the lesser of 3 evils ;)
[Update] Small code snippet :)
ORM-generated class in the data-layer:
public class Book : IBook
{
public string ISBN {get; private set;}
}
IBook is found in the business-logic layer, along with a book wrapper:
public interface IBook
{
string ISBN {get;}
}
public class BookWrapper //Or whatever you want to call it :)
{
//Create a new book in the constructor
public BookWrapper()
{
BookData = new Data.MyORM.CreateNewBook();
}
//Expose the IBook, so we dont have to cascade the ISBN calls to it
public IBook BookData {get; protected set;}
//Also add whichever business logic operation we need here
public Author LookUpAuther()
{
if (IBook == null)
throw new SystemException("Noes, this bookwrapper doesn't have an IBook :(")
//Contact some webservice to find the author of the book, based on the ISBN
}
}
I don't know if this is a recognizable design-pattern, but it's what I use, and so far it has worked quite well :)
You are feeling the pain of the mismatch between the different paradigms of relational data and objects.
By this, I mean that the worlds of relational data and objects are very, very different from each other. For example, in database-land all data is public. In object-land, data is encapsulated and very specifically not made public. In database-land, all relationships are bi-directional, whereas in object-land an object in a collection might not have any reference to its parent. In database-land, procedures are global. In object-land, procedures are local to the object which contains the acted-upon data.
For these reasons and more, an approach which creates objects that represent database tables is inherently going to be painful. While yes, technically they are objects, they have the semantics of database-land. Making them live in object-land, as you have experienced, is difficult if not impossible. This can be referred to as data-first.
A better approach (in my opinion) is to focus on mapping objects to the database, rather than mapping the database to objects. This can be referred to as object-first, and is supported very well by NHibernate. This approach emphasizes the fact that a database is an implementation detail of a system, not a design precept.
I realize this doesn't specifically answer your question, but I hope it provides some context as to why you are having a hard time conceptualizing your entities: they are tables first and entities second.

Categories

Resources