LinQ ORM Data Objects and Inheritance - linq

I'm thinking about how to do this, but I have several different shapes of Data in my Database, Articles, NewsItems, etc.
They All have something in common, they all have IDs (in the DB they're named ArticleID, NewsID etc. )
They all have a Title
They all have BodyText.
They all have a Status
They all have a DateAdded
What I'd like to do is standard class inheritance.
I'd like a Master Class (I don't need to write this to the database) called Content with fields like:
ID
Title
SubTitle
BodyText
Status
AddedDate
I'm not sure how I can do this with the ORM. Why I want this is because then I can pass a list of COntent to my UserControl which is responsible for Rendering it. It will only need the information that is common to all objects.
Is this even possible?

This is what Interfaces are for. Have each class implement an IContent interface that contains your Title, BodyText, Status and DateAdded properties. Now you can pass around a collection ( List<IContent> ) around that could containt different types of content.
If you're using LinqToSql you can create partial class files to have the autogenerated classes implement the interface you want.
public partial class SomeContent : IContent

I'm not sure whether you're talking about LINQ to SQL, but there are a few resources online about how to create inheritance with it:
LINQ To SQL Discriminator Column Example - Inheritance Mapping Tutorial
Inheritance in LINQ to SQL Screencast
...and more.
HTH

I found one page that looks like it has something along the lines of what I'm looking for (The last post)... but I'm not sure about using weakly typed objects:
LINQ inheritance

Related

linq to sql, how to define DataContext without specifying Table properties

My intent is to create a generic (not in C# meaning) database model for Windows Phone using linq to sql. User of such model should be able to pass an array of his data object types (classes marked with Table attribute) to model's contstructor, and then model should take care about adding related tables to database and provide API for CRUD operations.
But then I've found out that in order to add tables to database, your data context (class inherited from DataContext class) have to declare each table as a property! That's embarrassing. Does this fact mean that my idea is not implementable? Because I obviously cannot add properties to my DataContext-based in the runtime.
So my question is, am I right in my judgments? If yes, are there some workarounds to solve this issue?
Thanks in advance.
EDIT: better question tagging, for somebody finally notice this.
You do not need to use a strongly typed DataContext (a class inheriting from DataContext and declaring properties for each table). You can do something like the following instead
var context = new DataContext("connection string", new AttributeMappingSource());
var table = context.GetTable<T>();
where T is some type marked with the Table attribute.

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.

Correct way to map DTOs for complex pages

I have an MVC app and I have started to use DTOs exclusively to send data to views. I am using AutoMapper in order to ease this process.
Imagine I have a Customer that has many Orders. To display a simple customer overview page I can use AutoMapper with a simple DTO class that maps the Customer name, address etc. To map the orders I can AutoMapper a List<> of Customer.Orders to a more simple List<CustomerOrderDTO>.
I am now stuck on pages where I want both in the same view. Perhaps a simple headline with the customer name and phone number, then a list of orders. In some cases partials are the perfect solution, but not all.
So my question is how a DTO for a page such as this should look, and how that should be mapped (preferably using AutoMapper). In my research so far, I can't see how AutoMapper can map embedded enumerables like this.
when you create your mappings, ignore the collections/enumerables and just map simple objects to simple objects, for example CreateMap<Order, CustomerOrderDTO>()
when you execute the mapping, you can use collections and AutoMapper will just do the right thing, for example Map<IEnumerable<Order>, IEnumerable<CustomerOrderDTO>>()
if you're mapping an object contains the collection, for example Customer to CustomerDTO, where each one has it's collection of orders, as long as you've done CreateMap for the customer objects and CreateMap for the Order objects, the enumerable will just map automatically, unless you specifically set it to be ignored in the customer mapping.

generic class constraints: 2 types

i want to create a generic class that would accept T.
T is an object coming from Entity Framework representing a Table, or a View of that table.
properties on both would be the same.
I would like to create a generic class, that will accept the table or view, and construct a linq query based on the properties.
so i would need to do something like..
class Foo Where T : myTable or T : myView
so that later i could use the strongly typed properties to construct my predicates.
How could i achieve something like this?
the way i construct my query looks something like this:
if (critera.IsTradeDate)
predicate = PredicateUtility.And(predicate, t => t.DateTrade >= critera.FromDate);
the t is the type that needs to be strong, and properties used will be the same on table and view. So in this case, t should represent either my table or my view, to re-use the code, but still leverage entity framework..
Create an interface ITableOrView (or some better name). Apply the interface to both partial classes for your Entities that are the Table or View.
Create your generic class with where T : ITableOrView
Now you can use the interface types.
BUT you can't use interfaces in many places in Entity Framework queries so you'll actually need to delegate that work back to the 'T' class itself.

LINQ to SQL classes to my own classes

I'm looking at using LINQ to SQL for a new project I'm working on, but I do not want to expose the LINQ classes to my applications. For example, do an select in link returns a System.Linq.IQueryable<> collection. As well, all the classes generated to represent the database use Table, Column, EntityRef classes and attributes. It's fine if my data access layer has LINQ dependancies, but I don't want my application to.
So my thoughts are that I will have to use the LINQ to SQL generated classes as intermediate classes that are not exposed outside of my data access layer, and create my own classes which the application can use. What is the easiest/effecient way to get the data from the LINQ to SQL classes into my own classes?
I totally agree with your thinking - I would try to avoid exposing LINQ to SQL entities directly to the world.
I would definitely recommend using a "domain model" of your own, either a 1:1 mirror of the underlying LINQ to SQL entities, or a different one.
As long as you have a domain model that is quite similar to the underlying LINQ to SQL entities, you can use tools like AutoMapper to easily shuffle data between your LINQ to SQL entities and your domain model classes. It should be pretty easy and flexible to do it that way!
Rob Conery published a webcast series entitled the MVC-Storefront where he introduces a variation of the repository pattern that accomplishes what you want.
I've used ideas from the screencast on a reasonably large project and was quite pleased with the results.
There are, however, issues with the pattern, particularly around concurrency and detached scenarios that you will want to think about up front before fully committing to it.
I detailed some of my pain with concurrency in this pattern here.
I'll be interested in the responses you get because I'm considering the exact same thing. I want to use the L2S entities classes on our backend but use much lighter-weight entities for application consumption.
Randy
I would advise against using LINQ to SQL on a new project, since Microsoft will no longer be developing this project, except for maybe fine-tuning some issues. LINQ to SQL is perfectly usable and is acceptable, but I would not advise new projects to use it. If you like LINQ to SQL, you should definately look into using Entity Framework instead of LINQ to SQL.
This is my current incarnation of how I am going about doing this:
I have a DataContext class that I created by adding a LINQ to SQL class, and droping tables onto the designer. I called the class MyDataContext and put it in a namespace called Linq. My database has a table called Tag, which generated a class, also in the Linq namespace. I changed all the accessors to internal, so they would not be visible outside of the data access layer.
namespace Linq
{
[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDb")]
internal partial class MyDataContext : System.Data.Linq.DataContext
{
...
}
[Table(Name="dbo.vTag")]
internal partial class Tag
{
....
}
}
I then created a class called DataAccess which is what will be exposed to any application that references the assembly. I also created my own Tag class. The DataAccess class and my new Tag class are in a different namespace called Data to avoid collisions with the generated classes which are in the Linq namespace. I use Linq to Sql to query for an IList of Linq.Tag objects, then I use Linq to generate me a list of Data.Tag objects from the Linq.Tag objects.
I'd like to hear comments on this to see if there's a more performant way to do this, or one that requires less code. I also wasn't too happy with my use of duplicate class names (Tag) so I'm interested to hear any ideas on naming suggestions too.
namespace Data
{
public class DataAaccess
{
public IList<Tag> List_Tags()
{
using (Linq.MyDataContext dal = new Linq.MyDataContext ())
{
IList<Linq.Tag> lstTags = (from c in dal.Tags select c).ToList();
return (from tag in lstTags
select new Data.Tag()
{
ID = tag.ID,
Name = tag.Name,
Parent_ID = tag.Parent_ID
}).ToList();
}
}
}
}
What you are proposing is having two separate models. That means boilerplate code, which I've found is not necessary. I have more or less the same idea as you, but realized that this would be useless. I've suggested Entity Framework in another answer in this thread, and I want to make that point again here.
What you end up with is a model-soup, where you have to maintain two models instead of just the one. And that is definitely NOT desirable.
To go from the LINQ to SQL classes to your classes is a matter of some fairly straightfoward LINQ to Objects (or just initialisation for single objects).
More fun is going back from your model to the LINQ to SQL objects but this is fairly standard stuff (although something I'm still working out or I'd find you some specific references).

Resources