EF 5 Model First Partial Class Custom Constructor How To? - entity-framework

EF has generated for me some partial classes, each with a constructor, but it says not to touch them (example below), now if I make my own secondary partial class and I want to have a constructor that automatically sets some of the fields how do I do so as it would conflict?
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Breakdown.Models
{
using System;
using System.Collections.Generic;
public partial class Call
{
public Call()
{
this.Logs = new HashSet<Log>();
}
...
}
}

Partial methods can help you here, in the T4 Templates define a body-less partial method and call that inside the constructor.
public <#=code.Escape(entity)#>()
{
...
OnInit();
}
partial void OnInit();
Then in your partial class define the partial method and place inside that what you want to do in the constructor. If you don't want to do anything then you don't need to define the partial method.
partial class Entity()
{
partial void OnInit()
{
//constructor stuff
...
}
}
http://msdn.microsoft.com/en-us/library/vstudio/6b0scde8.aspx

This is not possible.
Partial classes are essentially parts of the same class.
No method can be defined twice or overridden (same rule apply for the constructor also)
But You can use below mentioned Workaround :
//From file SomeClass.cs - generated by the tool
public partial class SomeClass
{
// ...
}
// From file SomeClass.cs - created by me
public partial class SomeClass
{
// My new constructor - construct from SomeOtherType
// Call the default ctor so important initialization can be done
public SomeClass(SomeOtherType value) : this()
{
}
}
for more information check Partial Classes, Default Constructors
I hope this will help to you.

I wanted to do the same recently and ended up modifying the T4 template so I could implement my own parameterless constructor manually. To accomplish this you can remove the constructor from the generated classes and move the instantiation of collections etc to outside the constructor so this:
public Call()
{
this.Logs = new HashSet<Log>();
}
becomes this:
private ICollection<Log> logs = new HashSet<Log>();
public virtual ICollection<Log> Logs
{
get { return this.logs; }
set { this.logs = value; }
}
The drawback I suppose is that the generated classes are not as "clean". That is you can't just have auto-implemented properties for your complex/nav types.
In your model.tt file you can prevent the constructor generation by removing the below code, commenting it out or by just putting in a false into the conditional so it never gets executed:
if (propertiesWithDefaultValues.Any() || complexProperties.Any())
{
#>
public <#=code.Escape(complex)#>()
{
<#
foreach (var edmProperty in propertiesWithDefaultValues)
{
#>
this.<#=code.Escape(edmProperty)#> =
<#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
<#
}
foreach (var complexProperty in complexProperties)
{
#>
this.<#=code.Escape(complexProperty)#> = new
<#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
<#
}
#>
}
Then below this you need to do some modification where properties are generated for your complex and navigation types. Add a private var with object instantiation and a property for accessing the private var for each of these eg:
if (complexProperties.Any())
{
foreach(var complexProperty in complexProperties)
{
//generate private var + any instantiation
//generate property for accessing var
}
}
Depending on the complexity of your model there may be other areas you need to modify. Hopefully this gets you started.

If I well understand the question, you need this constructor when creating a new entity, that is an entity that was not persisted before.
My case was to set a default value to all datetime, that is initalize them to "the begining of time" : 1900-01-01.
In this case I use an entity factory
public static T GetNewEntity<T> () {
T e;
try {
e = Activator.CreateInstance<T>();
} catch {
e = default(T);
}
SetDefaults(e);
return e;
}
Each time I need a new Entity I use
Entity e = GetNewEntity<Entity>();
with SetDefaults as :
public static void SetDefaults (object o) {
Type T = o.GetType();
foreach ( MemberInfo m in T.GetProperties() ) {
PropertyInfo P = T.GetProperty(m.Name);
switch ( Type.GetTypeCode(P.PropertyType) ) {
case TypeCode.String :
if ( P.GetValue(o, null) == null )
P.SetValue(o, String.Empty, null);
break;
case TypeCode.DateTime :
if ( (DateTime)P.GetValue(o, null) == DateTime.MinValue )
P.SetValue(o, EntityTools.dtDef, null);
break;
}
}
}
full code is here
It could be rewrittent to consider the entity type and so on...

Add a base class:
public class CallBase
{
protected CallBase()
{
Initialize();
}
protected abstract void Initialize();
}
Add the partial class implementation in another file
public partial class Call: CallBase
{
protected override void Initialize();
{
...
}
}
The drawback is that the Initialization method will be called before the all collection creature.

Related

this singleton has way can be improved?

i was using google's singleton but this must need too many reference.
example, when I have to use another class in my Player class that used singleton, I must be using reference three time. Like this : Player.instance.another.blank=0;
my singleton
public static Player instance;
public void Awake()
{
if(instance ==null){
instance=this;
}
else
{
if(instance!=this){
Destroy(this.gameObject);
}
}
Is there any reason to destroy the instance? Even so, we are not updating the existing instance immediately after destroying it whenever a player is added.
I have a singleton Gist that I usually use: https://gist.github.com/xepherys/34d3d5ce3f44749e8649a25b38127347
It has decent comments for anyone unfamiliar with singletons, and is threadsafe. You can remove everything except the lazy field and the constructor region. I use this as the basis for Manager classes.
using System;
// Update namespace as needed
namespace WhatsYourName
{
/*
This is the name of your threadsafe Singleton - change "SingletonLazyThreadsafe" to value that makes sense, and be sure to use your
editors [Rename] option, or update all values to match.
Just because the Singleton itself is threadsafe does not mean that all methods that might be contained are automatically threadsafe.
If threading is important, use threadsafe variables, such as:
System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>
https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2
rather than:
System.Collections.Generic.Dictionary<TKey,TValue>
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2
Alternatively, lock() can be used in a pinch, but there is the potential for slight performance hits.
Any field, property, or method not marked with "// REQUIRED" means that it's just a sample and can be removed or changed as needed.
Comments are inline as a reminder and as a point of education for those not familiar with Singletons.
Initial snippet added 12/08/2018 - JSW (Xepherys).
*/
public class SingletonLazyThreadsafe
{
#region Fields
// Private
private static readonly Lazy<SingletonLazyThreadsafe> lazy = new Lazy<SingletonLazyThreadsafe>(() => new SingletonLazyThreadsafe()); // REQUIRED
private int changeCount;
private int myInteger;
private string myString;
// Public
public char MyPublicChar; // Note: Even though it's a field, if it's publicly accessible, I generally capitalize the first letter. This is a personal design choice. Most folk tend to use lowercase for fields regardless of their accessibility level.
#endregion
#region Properties
// Note: Private getter/setter for private field.
private int ChangeCount
{
get
{
return this.changeCount;
}
set
{
this.changeCount = value;
}
}
// Note: Public getter/setter for private field.
public int MyInteger
{
get
{
return this.myInteger;
}
set
{
this.myInteger = value;
}
}
// Note: Public getter / protected setter for private field. This allows a {get} from anywhere, but only a {set} from inside the class or derived classes.
public string MyString
{
get
{
return this.myString;
}
protected set
{
this.myString = value;
}
}
#endregion
#region Constructors
private SingletonLazyThreadsafe() // REQUIRED
{ }
public static SingletonLazyThreadsafe Instance // REQUIRED
{
get
{
return lazy.Value;
}
}
#endregion
#region Methods
// Note: This is a public method that just changes the myInteger field. It's useless since the property is public, but it's just an example. It also call IncreaseCount().
public void IncrementInteger(int value)
{
this.MyInteger = value;
IncreaseCount();
}
// Note: This is a public method that just changes the myString field. It's useless since the property is public, but it's just an example. It also call IncreaseCount().
public void ChangeString(string value)
{
this.MyString = value;
IncreaseCount();
}
// Note: This is a private method, which means it can only be called by other methods in this class, and not publicly or outside of the class. While it could directly change
// 'changeCount', I also have it making changes via the private 'ChangeCount' property, which is also only accessible inside the class.
private void IncreaseCount()
{
this.ChangeCount++;
}
#endregion
}
}

How do I combine a Controlled Lifetime relationship type (i.e. Owned<T>) with a delegate factory?

In my application, I have a service that requires a constructor parameter not resolved by Autofac, that I instantiate using a delegate factory:
public class Service
{
public Service(string parameter /*, ... other dependencies */)
{
}
public delegate Service Factory(string parameter);
}
This works great! I really love this feature.
I also like the Controlled Lifetime relationship, so I can let my component depend on a Func<Owned<ISomething>> like this:
public class Component
{
private Func<Owned<ISomething>> _somethingFactory;
/* constructor omitted for brevity */
public void DoSomethingUseful()
{
using (var ownedSomething = _somethingFactory())
{
/* Lots of useful code here */
}
}
}
My problem is that now I want to combine the two. I can't have an instance of Func<Owned<Service>> injected, because it needs that parameter, so my current solution is to abstract the factory away into another service, say IServiceFactory:
public interface IServiceFactory
{
Service Create(string parameter);
}
...implemented as such:
public class ServiceFactory : IServiceFactory
{
private Service.Factory _internalFactory;
public ServiceFactory(Service.Factory internalFactory)
{
_internalFactory = internalFactory;
}
public Service Create(string parameter)
{
return _internalFactory(parameter);
}
}
My component then becomes this:
public class Component
{
Func<Owned<IServiceFactory>> _serviceFactoryFactory;
/* ... */
}
The need for such a field name leaves a bad taste in my mouth to the point that I suspect there must be a cleaner way to handle this case.
Is there another way?
You could change your injected factory to include the string parameter:
private Func<string, Owned<ISomething>> _somethingFactory;
Then you can pass the string to the factory when you want to create a new instance:
public void DoSomethingUseful()
{
using (var ownedSomething = _somethingFactory("my parameter"))
{
/* Lots of useful code here */
}
}
I've created a .NET Fiddle with a small working sample.

EF Code First Migration: How to inherit MigrateDatabaseToLatestVersion

I want to derive a class from MigrateDatabaseToLatestVersion in my project.
public abstract class BaseDatabaseInitializer<TContext> : MigrateDatabaseToLatestVersion<TContext, MigrationConfiguration>
where TContext : DbContext
MigrationConfiguration class looks like this
internal sealed class MigrationConfiguration : DbMigrationsConfiguration<QAdminDbContext>
{
public MigrationConfiguration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(QAdminDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
But I am not allowed to do so and am getting an error
"Inconsistent accessibility: base class 'System.Data.Entity.MigrateDatabaseToLatestVersion<TContext,Lutron.Application.QAdmin.Database.EntityConfiguration.MigrationConfiguration>' is less accessible than class 'Lutron.Application.QAdmin.Database.BaseDatabaseInitializer<TContext>' E:\Proj\Lutron\Code\src\Lutron\Gulliver\QAdmin\DataAccess\Database\BaseDatabaseInitializer.cs 17 27 Database"
This is due to the fact that MigrateDatabaseToLatestVerion class has explicitly defined where clause for MigrationConfigurationContext.
Since, in my custom class, I have explicitly defined 'Configuration' class, I can't add where clause.
The error occurs because the abstract initializer class is a public class, but the migrations class is internal. Change them both to public classes or both to internal classes, but then there is another issue.
The C# compiler will see that someone is allowed to try BaseDatabaseInitializer<SomeOtherContext>, but the MigrationConfiguration class isn't convertible to a migration with a type parameter of SomeOtherContext, so it won't allow the code to compile.
There are some possible solutions, but I think it depends on what you are trying to achieve. If you want more control over how and when the migrations execute I'd probably take a different approach and implement IDatabaseInitializer, which still allows you to plug the class into the application as a database initializer, something like:
public abstract class BaseDatabaseInitializer<TContext> :
IDatabaseInitializer<TContext> where TContext : DbContext
{
private readonly DbMigrationsConfiguration<TContext> _migrations;
protected BaseDatabaseInitializer(DbMigrationsConfiguration<TContext> migrations)
{
_migrations = migrations;
}
public void InitializeDatabase(TContext context)
{
new DbMigrator(_migrations).Update();
}
}

Forcing the use of a specific overload of a method in C#

I have an overloaded generic method used to obtain the value of a property of an object of type PageData. The properties collection is implemented as a Dictionary<string, object>. The method is used to avoid the tedium of checking if the property is not null and has a value.
A common pattern is to bind a collection of PageData to a repeater. Then within the repeater each PageData is the Container.DataItem which is of type object.
I wrote the original extension method against PageData:
public static T GetPropertyValue<T>(this PageData page, string propertyName);
But when data binding, you have to cast the Container.DataItem to PageData:
<%# ((PageData)Container.DataItem).GetPropertyValue("SomeProperty") %>
I got a little itch and wondered if I couldn't overload the method to extend object, place this method in a separate namespace (so as not to pollute everything that inherits object) and only use this namespace in my aspx/ascx files where I know I've databound a collection of PageData. With this, I can then avoid the messy cast in my aspx/ascx e.g.
// The new overload
public static T GetPropertyValue<T>(this object page, string propertyName);
// and the new usage
<%# Container.DataItem.GetPropertyValue("SomeProperty") %>
Inside the object version of GetPropertyValue, I cast the page parameter to PageData
public static T GetPropertyValue<T>(this object page, string propertyName)
{
PageData data = page as PageData;
if (data != null)
{
return data.GetPropertyValue<T>(propertyName);
}
else
{
return default(T);
}
}
and then forward the call onto, what I would expect to be PageData version of GetPropertyValue, however, I'm getting a StackOverflowException as it's just re-calling the object version.
How can I get the compiler to realise that the PageData overload is a better match than the object overload?
The extension method syntax is just syntactic sugar to call static methods on objects. Just call it like you would any other regular static method (casting arguments if necessary).
i.e.,
public static T GetPropertyValue<T>(this object page, string propertyName)
{
PageData data = page as PageData;
if (data != null)
{
//will call the GetPropertyValue<T>(PageData,string) overload
return GetPropertyValue<T>(data, propertyName);
}
else
{
return default(T);
}
}
[edit]
In light of your comment, I wrote a test program to see this behavior. It looks like it does go with the most local method.
using System;
using Test.Nested;
namespace Test
{
namespace Nested
{
public static class Helper
{
public static void Method(this int num)
{
Console.WriteLine("Called method : Test.Nested.Helper.Method(int)");
}
}
}
static class Helper
{
public static void Method(this object obj)
{
Console.WriteLine("Called method : Test.Helper.Method(object)");
}
}
class Program
{
static void Main(string[] args)
{
int x = 0;
x.Method(); //calls the object overload
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.WriteLine();
}
}
}
To make sure the nesting is not affecting anything, tried this also removing the object overload:
using System;
using Test.Nested;
namespace Test
{
namespace Nested
{
public static class Helper
{
public static void Method(this int num)
{
Console.WriteLine("Called method : Test.Nested.Helper.Method(int)");
}
}
}
static class Helper
{
public static void Method(this string str)
{
Console.WriteLine("Called method : Test.Helper.Method(string)");
}
}
class Program
{
static void Main(string[] args)
{
int x = 0;
x.Method(); //calls the int overload
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.WriteLine();
}
}
}
Sure enough, the int overload is called.
So I think it's just that, when using the extension method syntax, the compiler looks within the current namespace first for appropriate methods (the "most local"), then other visible namespaces.
It should already be working fine. I've included a short but complete example below. I suggest you double-check your method signatures and calls, and if you're still having problems, try to come up with a similar short-but-complete program to edit into your question. I suspect you'll find the answer while coming up with the program, but at least if you don't, we should be able to reproduce it and fix it.
using System;
static class Extensions
{
public static void Foo<T>(this string x)
{
Console.WriteLine("Foo<{0}>(string)", typeof(T).Name);
}
public static void Foo<T>(this object x)
{
Console.WriteLine("Foo<{0}>(object)", typeof(T).Name);
string y = (string) x;
y.Foo<T>();
}
}
class Test
{
static void Main()
{
object s = "test";
s.Foo<int>();
}
}

Cast a CustomList<CustomClass> to IList<Interface>

(This is .Net 3.5) I have a class FooList which implements IList and a class FooClass which implements IFoo. A user requires IList<IFoo>. In my implementation, I create a FooList<FooClass>, called X. How do I code my return so that my FooList<FooClass> X becomes his IList<IFoo>?
If I try
return X.Cast( ).ToList( );
he gets an IList<IFoo>, but it is not my FooList; it is a List, and a new one at that.
This isn't going to work out, because a FooList<FooClass> is not an IList<IFoo>. This is why:
var myList = new FooList<FooClass>();
IFoo obj = new SomeOtherFooClass();
IList<IFoo> result = (IList<IFoo>)myList; // hypothetical, wouldn't actually work
result.Add(obj); // uh-oh, now myList has SomeOtherFooClass
You need to either make a copy or use an interface that is actually covariant on the contained type, like IEnumerable<T> instead of IList<T>. Or, if appropriate, you should declare your FooList<FooClass> as an FooList<IFoo> from the get-go instead.
Here is a small implementation that demonstrates my second suggestion:
public interface IFoo { }
public class FooClass : IFoo { }
public class FooList<T> : IList<T>
{
public void RemoveAt(int index) { /* ... */ }
/* further boring implementation of IList<T> goes here */
}
public static void ListConsumer(IList<IFoo> foos)
{
foos.RemoveAt(0); // or whatever
}
public static IList<IFoo> ListProducer()
{
// FooList<FooClass> foos = new FooList<FooClass>(); // would not work
FooList<IFoo> foos = new FooList<IFoo>();
foos.Add(new FooClass());
return foos; // a FooList<IFoo> is an IList<IFoo> so this is cool
}
public static void Demo()
{
ListConsumer(ListProducer()); // no problemo
}