Using Nested Classes with Entity Framework - c#

I've tried to do this in the designer, but I wasn't able to figure it out. Is it possible to persist nested classes using Entity Framework?
Note: I am just curious whether this is possible or not. I can't think, at this point, if there would ever be a reason to do this, but it might be nice to know how if it is possible.
Example:
public class NormalClass
{
public class NestedClass { }
}
Update:
Danny Varod had a good idea for how to accomplish this. When I have some spare time, I'm going to try it out, and I'll post the results on here, unless someone else gets to it first.

EF classes are declared partial, so you can add whatever you want to them.
Note that the inner-class's properties won't be persisted to the DB, if you want that, use a navigation property instead.

A nested class in .NET is basically the same as a class within another level of namespace (accept for the fact the inner class can access private parts of outer class, as Ladislav Mrnka pointed out - you could use internal instead of private to get around this), there is no change in behaviour (unlike in Java), so there is not much point in using nested classes.
You can define sub objects using complex properties or using a navigation properties, however, complex properties have limited capabilities (no navigation properties or keys in them) and neither are created as nested classes.
To force EF to use nested classes, you could try creating the classes yourself, then mapping them either with a Code-First approach or by cancelling the auto-creation of the class and writing them yourself (or changing the .tt file to created classes nested) and then editing the .emdx as an xml to map entity to a different class.

Related

Entity Framework - Abstract base class without mapping to DB table

I have a situation where I have 4-5 very similar classes which I'd like to re-factor to use an abstract base class.
The idea behind this would be allow methods which could be used by each class whilst adhering to DRY principles.
The problem I have is that these classes are Entity classes generted from EF4 and each time I try to alter my model it seems to break down.
What's the best/recommended, method to add a base class into my EF model and make the existing classes in the model inherit from this as a base? At the moment I've got no problem adding the base class, giving it an ID property as it seems to require, and then creating the inheritence, but EF then moans about
'Error 3024: Problem in mapping fragments starting at line 18563:Must specify mapping for all key properties (MyBaseType.ID) of the EntitySet MyBaseType.'
In this situation I don't want the base type to be persisted to the DB, purely used as a container for base methods common to all the classes which inherit from it. It feels like I'm missing something simple here but I can't for the life of me see it.
Any ideas on how to add in a base class in this way? Or should I just be adding the base class in code and bypassing the model somehow?
EDIT: As further information, take an example where there are say 3 types, MortageApplicationForm, BankAccountApplicationForm and CreditCardApplication form. They are currently stored in 3 different tables, with a set of different fields.
What I'm trying to do, is create a base class of say 'Form' which will have the common fields in it.
At a simple level, say that each table has a primary key ID field called, 'CreditCardFormID', 'BankAccountFormID' etc What I'd like to do it create a base 'Form' class with a property 'ID' which for the case of one table will map to 'CreditCardFormID' and another 'BankAccountFormID'.
I'm happy to do this mapping in partial classes (as I don't want to persist 'ID' to the DB) I simply want to use it in code, so I can write generic methods for things like LoadForm(int ID) without needing to write huge switches for each entity type, or specific methods for each entity type.
I managed to find a work around for this by rejigging things slightly. Firstly, I did not have the time available to rework the model (which I think would have been the best solution) too much of the system has already been developed with the existing structure to rip it all apart at this point.
The solution so far, has been to create a static helper class to contain business logic which is generic accross in my example, the 3 different account types.
This was coupled with an 'IAccount' interface, allowing the helper class to take an IAccount instance as a parameter (allowing the passing of any particular account type.) This interface contained all the common properties accross the 3-4 concrete classes. It was important to note that in order to create generic methods which I could call on all the classes I was not able to use any other properties specific to the class.
Within the helper methods, I needed to switch my concrete XYZEntities instance to a more generic 'ObjectContext' object and then use the methods such as 'AddObject' rather than 'AddBankAccountForm', 'AddCreditCardForm' etc explicitely.
This involved a tiny bit of GetType()'ing to ensure the object was passed to the correct ObjectSet, but seems to work as desired.
There are 3 patterns for this:
Table per Class Hierarchy. All concrete types in the inheritance heirarchy are stored in one table.
Table per Type. Each type in the inheritance is stored in it's own table.
Table per Concrete class. A table for each concrete class but no table for the abstract class.
In your case with the existing tables the Table per Concrete class looks like the best fit.
There is a good description of these options in this book

C#, is it okay to use nested classes for logical structure?

I am having a bit of a debate about the use of nested classes. The situation is that a class name makes sense to be repeated in two or more places, and while there is moderate similarity between each of the different instances, they are generally different. The nested classes are not often (if at all) needed beyond the scope of their parent class.
So then, rather than just coming up with three different class names, this seems to make more sense to me.
class A {
class B {
}
class M {
class B {
}
}
class Q {
class B {
}
}
The obvious problem with that is not functionality, but rather consistency/repetition. I was wondering if other developers have ever struggled with the same thing, and what some of the opinions were.
The .net Design Guide advises against it:
"Do not use public nested types as a logical grouping construct; use namespaces for this."
"Avoid publicly exposed nested types. The only exception to this is when variables of the nested type need to be declared in rare scenarios such as subclassing or other advanced customization scenarios."
That's also what the base class library does: In the System.Web.UI namespace, you have DataGridItem, DataListItem, ListViewItem, MenuItem, RepeaterItem, etc. All of these could be called Item and nested inside DataGrid, DataList, etc. However, this would violate the two principles outlined above.
It looks okay when your classes are small. Once they get bloated, you really start thinking about moving them in separate files.
More to your point, if you want to use both A.B and M.B in the same code you have to always type A.B and M.B, which can be a pain.
If class B has any similarities between each inner class instance, would it make sense for you to abstract the similarities of B to a base class that exists alongside A, M, and Q? (I think so.) Then your inner classes, while they may have the same name, would be a little cleaner.
With that said, this type of structure can be seen for things like Metadata in an MVC application. In that instance you'd have something like:
[MetadataType(typeof(A.Metadata))]
class A
{
protected class Metadata
{
...
}
}
[MetadataType(typeof(B.Metadata))]
class B
{
protected class Metadata
{
...
}
}
In these case the inner classes each serve the same purpose but their implementations vary with each parent class. Also, with the Metadata definitions here, it makes a lot of sense to keep a class that helps describe its parent as an inner class. If there's any chance you might want to re-use the inner classes elsewhere then I would move them outside of their parents.
I think it's a little atypical to see this in practice otherwise. I'm sure there are good examples, but I bet there are more bad examples of this type of pattern.
I would say it is sometimes ok, but usually not a good design, to use private nested classes. I once refactored an existing very large class in my project to give it private nested classes. The reason why I did this was that some methods took dozens of parameters and this gave them a more logical grouping. In this sense I see nested classes as a good quick fix. It made sense because no one outside that class had any use for any of those fields.
Generally, I would shy away from using nested classes in an initial design - and think twice before considering them in a redesign. In maintenance, if you have the time, it is better to redesign the whole class and split them out into separate classes in separate files that are internal.
I think this strategy is also better for testability than using nested classes is. Due to greater dependencies with the outer class and other classes in the application, my refactored nested classes weren't much easier to unit test than the original large class that passed around many parameters. If you split nested classes so that they are on their own, you can write more discrete unit tests that actually test units rather than, effectively, combining the unit tests for the outer class and the inner class. This will give you more confidence in saying, "Yes, the inner class works at the unit test level" and "Yes, the outer class works at the unit test level" (which also tests how it fits together with the inner class, e.g. in computing formulas).
I understand your sample is sort of contrived. Still, if your class names are similar enough - or identical - you really shouldn't make them nested classes. As a general rule you should shy away from using nested classes at all.
If I'm remembering correctly, the .NET Framework Guidelines recommends against using nested classes as well. Nested Type Usage Guidelines is a little old (back to version 1.1), but the principles still apply.
Do not use nested types if the following are true:
The type must be instantiated by client code. If a type has a
public constructor, it probably should not be nested. The rationale
behind this guideline is that if a nested type can be instantiated, it
indicates that the type has a place in the library on its own. You can
create it, use it, and destroy it without using the outer type.
Therefore, it should not be nested. An inner type should not be widely
reused outside of the outer type without a relationship to the outer
type.
References to the type are commonly declared in client code.
Well you can use namespaces to do things like this too (just create a new folder in VS). Which is better for organising and will pretty much give you the same result.
But if the subclass is only relevant to the parent class then I don't see the harm in it.
Then again, if you are calling them the same thing I would guess they do a similar drop and you may want to look into abstraction, perhaps your parent classes could be done differently too. Really depends on what you need them to do though
I like doing that, for me it makes the use more clearer and especially finding names less of a problem. But usally i try to limit this on private classes or public enums.
For example
class Text {
enum Alignment
class UIElement {
enum Alignment
or
class Quadtree {
private class Node
class Octree {
private class Node
Don't create a nested class if there is any chance (or business reason) that you'll have to use it in some other place (use namespace instead and dot not hesitate to create class with long name if you need to).
For instance I use nested class for DTO between my controller and my view, or in a class to represent a cache entry.
If you want to name them the same but have different types you could use different namespaces.
Namespace1.MyClass{}
Namespace2.MyClass{}
This will end up with two different types despite the classes being named the same.
It really depends on the functionality of the nested class. That is very similar to the way the C++ STL defined iterator differently in each class. There's nothing wrong with the practice, per se, as long as the concept of each is truly different based on the encompassing class.
It can be, somewhat, a matter of style and taste, but personally I don't see an issue as long as they are truly different and dependent on the definition of the encapsulating class. It does tend to get more confusing, though, if they are publicly visible outside the class. Thus, I would not personally expose the classes publicly.
There's nothing inherently wrong about nested classes, as long as you stick to the following rules of thumb:
Never public or internal. There are special cases, such as when you're using a nested class to implement IEnumerator. But even then, the class itself should be kept private, since instances of it are being returned as IEnumerator, and it's really just being done as a way to avoid junking up the namespace with classes that aren't supposed to be instantiated.
Keep them small. A private nested class that's really just used for storing and passing around data in a more organized way is fine, and can sometimes be a very useful tool. (Not entirely unlike how anonymous classes are useful.) But if you're looking to use them to package up large chunks of functionality, it becomes a code smell that suggests you might want to consider refactoring the outer class instead.

XmlDeserialization after renaming the classes involved

I have a bunch of xml serialized objects in a database.
But, I refactored and renamed the classes involved, so deserializing from the db is difficult.
I thought that by adding the term [XmlRoot("DB_Class_Name")] atop the renamed classes would fix the issue, but it doesn't appear to.
Is there a way to fix the issue using labels like [XmlRoot], [XmlElement] etc., without renaming my classes to their old classnames, and without writing a special deserialize function?
Also, are there any good sources on what is happening under the hood when using xmldeserializaiton and labels like [XmlRoot]?
First of all, [XmlRoot] etc. aren't labels, they're attributes.
Second, [XmlRoot] only affects the class when that class is used as the root element of the document. It has no affect when an instance of that class is used as a child or other descendant.
Use [XmlType] on the class, or [XmlElement] on a property that is of the type of the class.

Do private classes need to be accessed by properties?

I am using an instance of a private class as the state object supplied to a stream.BeginRead operation. (The class is private to my main stream reading/writing class.)
public class MainClass
{
// ...
private class ResponseState
{
public IResponse response;
public Stream stream;
public byte[] buffer = new byte[1024];
}
}
Access to the class is via the fields directly. Should I really be providing access to the class via properties in this case, even though it is only to be used for holding state?
Interested to know what others do.
It's not required by the C# language, but it is good practice never to expose a field directly for maintainability reasons - it is suggested to use a property instead.
See StyleCop SA1401: FieldsMustBePrivate.
TypeName - FieldsMustBePrivate
CheckId - SA1401
Category - Maintainability Rules
Cause
A field within a C# class has an access modifier other than private.
Rule Description
A violation of this rule occurs whenever a field in a class is given non-private access. For maintainability reasons, properties should always be used as the mechanism for exposing fields outside of a class, and fields should always be declared with private access. This allows the internal implementation of the property to change over time without changing the interface of the class.
Fields located within C# structs are allowed to have any access level.
How to Fix Violations
To fix a violation of this rule, make the field private and add a property to expose the field outside of the class.
If your class is purely state for the containing class then you could consider placing the members directly inside the class that uses them. If your class is more than just state (and I suspect it is) then it should follow the usual maintainability rules.
I would - encapsulation is useful inside the class as well as outside the class. By funneling all access to a member through a well know interface (i.e. the property) you are giving yourself the flexibility to add logic around that access later without changing calling code.
It may seem like overkill but honestly, given automatically implemented properties, it is so easy to declare a property that you may as well go ahead and use one to give yourself maximum flexibility.
In my organization, when a class was private or internal, and it's a entity class, we used public fields to access it.
However, since C# 3.0 we use automatic properties, so we always use properties to access private fields.
Anyway, the effect is the same, in our case it was to do the code more readable.
Best practice is to use properties for every member accessible by other types. Automatic properties at C# 3.0 makes this quite easy.
I have just done some reading on this a week or two ago. There are the two camps. One the majority say you must wrap in the property because my teacher said so and everyone else does it. They say that is easier to add extra logic to a property or more maintainable and some other weak reasons. The other camp, call themselves "the true OO guys" tend to be along the line of if you use properties at all you are doing it wrong (with some exceptions of course). Your case would be the exception as far as I can tell. Actually, thinking about it, they would probably still say you are doing it wrong :) Just cant win. Anyway, they also say if you are going to use them don't bother wrapping unless you need the extra logic in your setters and getters. Why slow your program down for nothing. (apparently they can measure how slow too).
I tend to use properties over fields as I do a lot of MVVM and need to implement INotifyPropertyChanged which requires them. In your case I wouldn't worry about wrapping them in properties just makes for pointless fat. But if it was in a class that needed a property then I would wrap them to keep things similar in that class.
If after all that you didn't wrap them, and needed to later, it's a right click refactor->encapsulate field to wrap a property if you have Resharper.

Adding a property without touching the class? (not inheritance)

I got a requirement in my project to add another property to some class.
Now I want to avoid changing the class because I figured it shouldn't be aware that he has this property (this property only has significance in the context of this project).
The way I thought to accomplish this was (Please critic this because I wanna know if there are simpler ways of doing this)
Adding a new singleton class that has a mapping between objects of my class and the type of the property I wanted to add
adding in this class an extension method (extension property?) to access the mapping and fetch the property.
Is there a simpler alternative?
Is this just unnecessary complexity? Maybe I should just add a new property to my class?
Thanks!
The design you've described is actually the one used by Microsoft to implement the DependencyProperty system and, in particular, Attached Properties, though in the greater context of a binding framework. That said, using a dictionary with 'attached' data is a very typical solution when you need to tag a class with additional context for a particular use, but don't want to modify the class.
Why do you say "not inheritance"? Surely the way to do this, if you don't want to alter the original class, would be to inherit from the original class and then add your property to the derived class?
BTW, there are only extension methods, not properties, so you can't do it via property.
I would suggest the DECORATOR pattern. I know you say you don't want to use inheritence, but sometimes it's cleaner to do so. The pattern only uses inheritance to define the interface.
An extension method makes sense and it's also relatively simple.
[visibility] [type] [methodName](this [class to extend] c, ... more args if necessary)
{
....
}
Adding a property doesn't break the class's interactions with existing clients, so that really seems the "simplest" approach.
More important, though, is the function of the new property. Is it logically part of the existing class? Change the class. If not, then an extension method might be preferable, but the problem then becomes the visibility of the extension method, and scope of its clients.
As always, complexity is the enemy. In this case, it sounds as though the singleton is a very complex solution, and the extension method is hit-and-miss, depending on scope and visilbity issues. Changing the class is simplest, and will probably make long-term maintenance much easier.
UPDATE: Note that extension methods are static, and that makes it pretty difficult for the extension method to hold data of any time, as a property would be exptected to do.
SECOND UPDATE: If you have access to the source for the class, consider making it a partial class, and put your new property in a separate file, but part of the same partial class. This keeps it separate from the main body of the class for maintenance purposes, and will work with most ORMs. However, there is a restriction that the partial class members have to be in a single assembly.
Define a Nullable values with their Properties(while the Property has significance only for this project)
your major problem is that you don't want to change the class itself because this requirement is ONLY for 1 project (build), i think you are considering SOLID priniciples, one of these principles is OCP (Open-Closed Principle), that is,
your Entity must be open for extension
but closed for modification

Categories