Inheritance in .Net EntityFramework 4.0 for similar database tables - c#

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; }
}

Related

Restrict access to a specific assembly

I'm working on a Winforms project with sql server, splitted in several assemblies.
The first assembly Entities contains DTO like :
public class Attribution
{
public short UserId { get; set; }
public User User { get; set; }
}
public class User
{
public short Id { get; set; }
}
The second assembly Repository is accessing Sql Server database.
The third assembly Service is the link between previous.
There are other layers but this is not the point. I need of course DTO's everywhere in the app.
In sql server, Attribution.UserId and User.Id are the same datas, located in 2 separate tables, linked by Ìnner join.
Attribution.UserId must be public because I need access from Repository,Service, etc... But I don't need it in the "logical" part of the app, what I need is Attribution.User.
At this time I have a UserService class in which there is a GetUser() method and I call this method to get the user in my AttributionService.GetAttribution() method.
Is there a way to restrict access to Attribution.UserId property to Service assembly? Or is it a kind of "good practice violation" to query a User DTO in AttributionService class?
Many thanks for your recommandation.
`
One option would be to make the set of the property internal and the use the InternalsVisibleTo attribute to grant access to internals to the Repository assembly.
Another less technical and more logical option would be to make the setter private and let the only way for it to be modified be the classes constructor. That way, your repository can get users built, but nobody can modify the ID later.
As a last option you could create an interface that contains only what the non-repository classes should have access to and pass this around. I'm not a big fan because that means you have to cast it back to your concrete class in the repository and that basically means your repository is lying (saying it accepts an ISomething, but then throwing if the ISomething is not the exact, concrete Something it expects).

Add corresponding non-database class to entity framework object

I am currently using EntityFrameworkCore 2.0.0.
The application I am creating is an online store product scraper. All stores are saved in the database, and each store has a scraper that implements IStoreScraper.
This is my store model:
public class Store
{
public int Id { get; set; }
public string Name { get; set; }
[NotMapped]
public IStoreScraper StoreScraper { get; set; }
}
I was wondering if it is possible to add the correct IStoreScraper object to the Store object when it is fetched from the database. Either by a value from the database or something else.
I also looked into injecting this in the constructor of the model, however, this violates the Dependency Injection pattern because each class has its own, already known, implementation.
Maybe I should even look at it from another perspective because this code should not be in a model class? Any ideas?
You can override the object materialized event and add it here, as mentioned in this answer;
How to Inject Helper Dependencies in Domain Model Entity Classes
However I would highly recommend against this. EF is meant to be your data model, you should have a business layer above this, which is the correct place to add dependencies like this.

What design pattern uses this approach for naming POCO classes

Ive got a library that handles the typical add/edit/update methods for an application. Im wondering what design pattern calls for naming the POCO classes that bundle the data for is sent back and forth. For example, one class might be similar to another, but needs to include a few other members for being sent back to the application vs the data that is sent in to be saved.
For example, this might be a POCO class that I would use to populate before in a library method before sending back to the app to be displayed/consumed.
public class CorporateDeptAssignmentInfo
{
public int Id { get; set; }
public int DivisionKey { get; set; }
public int DeptKey { get; set; }
public int Count { get; set; }
public string DeptName { get; set; }
public DateTime Corp_dept_from_date { get; set; }
public DateTime Corp_dept_to_date { get; set; }
}
On the other hand, if Im adding a new record, I might not want to populate all members.
I could either (a) make some members nullable or (b) create a new POCO class with a slightly different name for use with calling an update/add library method.
Are there any design patterns that mention the use of poco classes in either of the above ways?
It's either an Adapter, Decorator, or Facade. That's where I think it's heading anyway. You are looking for a way to present something, with modifications/simplification.
I don't know any specific design patterns for this scenario except the Data Transfer Object, but if your domain object actually does allow nullable values, why are your pocos not designed in the same way?
Personally I would make two POCO classes if the loading and adding / updating process takes different data. Both of these classes usually have an ID property that resort to the same domain object. Sometimes it's also useful if one of these classes encapsulate the other POCO, but I don't have this kind of of situation often in my code.
If you have further questions, feel free to ask.

Using IRepository pattern for multiple domain objects and multiple storage mechanisms

This is a VERY simplified example to demonstrate a question. While I am only showing two domain objects here, imagine there are many more with various parameters.
Let's say I have the following domain objects:
public class Object1
{
public string Identifier { get; set; }
public string Name { get; set; }
}
public class Object2
{
public string Identifier { get; set; }
public int ItemValue { get; set; }
}
A typical implementation of the Repository pattern would have an Object1Repository and an Object2Repository where each implements some IRepository interface that may include methods like AddObject, DeleteObject, GetObjectByIdentifier, etc... The repository would then know how to interact with a database to perform the suggested methods.
That is all well and good and I have used the Repository pattern in exactly this way many times. Now I have a problem where I have multiple different storage mechanisms; Oracle, SQLServer, text file, and XML file. What is the best design approach to support this idea? A repository of repositories? Basically what I am trying to achieve is to have multiple different objects be able to be stored to multiple different storage mediums and I am trying to apply the Repository pattern to this idea.
I am writing C# code, but I can read most other languages as well so a suggested approach doesn't necessarily have to be C#.
Please refer to How would I design a repository to handle multiple data access strategies? , I think this is what you want.
Basically assume you already have one IRepository interface having methods of CRUD and other generic methods refer by all your other repository, then you have multi implementations to IRepository interface.
After that use any IOC container (I use Windsor Castle) to resolve which implement's component should take part for this interface doing application setup.

Dynamic class creation

we have a data-layer which contains classes generated by outputs (tables/views/procs/functions) from database. The tables in database are normalized and are designed similar to OOP design ( table for "invoice" has 1:1 relation to table for "document", table for "invoice-item" has 1:1 relation to table for "document-item", etc...". All access to/from databaes is by stored procedures (for simple tables too).
Typical clas looks like (shortly):
public class DocumentItem {
public Guid? ItemID { get; set; }
public Guid? IDDocument { get; set; }
public DateTime? LastChange { get; set; }
}
public class InvoiceItem : DocumentItem {
public Guid? IDProduct { get; set; }
public decimal? Price { get; set; }
}
The problem is, the database tables has relations similar to multiple inheritance in OOP. Now we do a new class for every database output. But every database outputs are combination of "pure" tables in database.
The ideal solution would be (IMHO) tranform classes to interface, use the multiple implementation of interfaces, and then automaticly implement the members (this "table-classes" has only properties, and body of properties are always same).
For example:
public interface IItem {
Guid? ItemID { get; set; }
DateTime? LastChange { get; set; }
}
public interface IDocumentItem : IItem {
Guid? IDDocument { get; set; }
}
public interface IItemWithProduct : IItem {
Guid? IDProduct { get; set; }
}
public interface IItemWithRank : IItem {
string Rank { get; set; }
}
public interface IItemWithPrice : IItem {
decimal? Price { get; set; }
}
// example of "final" item interface
public interface IStorageItem : IDocumentItem, IItemWithProduct, IItemWithRank { }
// example of "final" item interface
public interface IInvoiceItem : IDocumentItem, IItemWithProduct, IItemWithPrice { }
// the result should be a object of class which implements "IInvoiceItem"
object myInvoiceItem = SomeMagicClass.CreateClassFromInterface( typeof( IInvoiceItem ) );
The database contains hunderts of tables and the whole solution is composed from dynamicly loaded modules (100+ modules).
What do you think, is the best way, how to deal with it?
EDIT:
Using partial classes is good tip, bud in our solution can not be used, because "IDocumentItem" and "IItemWithPrice" (for example) are in different assemblies.
Now, if we make change in "DocumentItem" table, we must go and re-generate source code in all dependent assemblies. There is almost no reuse (because can not use multiple inheritance). Its quite time consuming, if there are dozens of dependent assemblies.
I think it is a bad idea to automatically generate your domain model from your database schema.
So, you're really looking for some kind of mix-in technology. Of course, I have to ask why you aren't using LINQ to Entity Framework or NHibernate. O/RMs handle these problems by mapping the relational model into usable data structures that have APIs to support all of the transactions that you'll need to manipulate data in the database. But I digress.
If you are really looking for a mix-in technology to do dynamic code generation, check out Cecil at the Mono Project. It's a way better place to start than trying to use Reflection.Emit to build dynamic classes. There are other dynamic code generators out there but you may want to start with Cecil since the documentation is pretty good.
If you wish to continue auto-generating from the database and want to model multiple inheritance, then I think you have the right idea: Alter the tool to spit out interfaces with multiple inheritance, plus X num implementations.
You indicated elsewhere that a convention for inheritance vs. aggregation is enforced, and (as I understand) you know exactly how the resulting interfaces and classes should look. I understand that business rules are implemented elsewhere (maybe in a business rules engine?), so regenerating the classes should not require changes to dependent code, unless you want to take advantage of those changes, or existing properties have been altered or removed.
But you won't be done. Your classes will still have id's of related entities. If you want to make things easier for client code, you should have references to related entities (not caring about the related entity's ID), like this:
public class Person{
public Guid? PersonID { get; set; }
public Person Parent { get; set; }
}
That would make things easier on the client. When you think about it, going from ID's to references is work you have to do anyway; it's better to do it once in the middle tier than to let the client do it N number of times. Plus this makes your code less database-dependent.
So above all else, I recommend writing an OO wrapper for the auto-generated classes. You would program against this OO wrapper for almost everything; let only the data access layer interact with the auto-generated classes. Sure, you can't reuse inheritance metadata in the database (specified via conventions, I assume?), but at least you won't be carving a new path.
By contrast, what you have now looks like an anemic data model or worse.
The scenario is unclear to me.
If the code is generated, you don't need any magic: add some metadata to your database objects (e.g. Extended Properties in SQL Server) that flags the "basic" interfaces, and modify your generating template/tool to consider the flags.
If the question is about multiple inheritance, you are out of luck with .Net.
If the code is generated, you may also take advantage of partial classes and methods (are you using .Net 3.5?) to produce code in different source files.
If you need to generate code at run-time there are many techniques, not least ORM tools.
Now may you be a bit more explicit of your design context?

Categories

Resources