Disable conversion between VARCHAR and NVARCHAR when using Entity Framework over an existing SQL server database - sql

I have an existing database SQL server and I'm using EF6 over it. Let's assume I have the following code:
private sealed class Foo
{
public int Id { get; set; }
public string Bar { get; set; }
}
private sealed class FooConfiguration : EntityTypeConfiguration<Foo>
{
public FooConfiguration()
{
ToTable("Foos");
HasKey(e => e.Id);
Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
private class FooContext : DbContext
{
public FooContext(string connectionString)
: base(connectionString)
{
Database.SetInitializer<FooContext>(null);
}
public virtual DbSet<Foo> Foos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new FooConfiguration());
}
}
Usage:
const string bar = "حالياً البحث عبر جوجل";
int fooId;
using (var db = new FooContext(connectionString))
{
var foo = db.Foos.Add(new Foo { Bar = bar });
db.SaveChanges();
fooId = foo.Id;
}
using (var db = new FooContext(connectionString))
{
var foo = db.Foos.First(f => f.Id == fooId);
if (foo.Bar != bar)
{
Console.WriteLine("Oops!");
}
}
What can possibly go wrong? Well, if the Bar column has type VARCHAR(MAX) instead of NVARCHAR(MAX), then we are in a bad position, because VARCHAR cannot properly store that string of Unicode characters, so we get a bunch of question marks instead.
So, the question is: can I some how disable this conversion between VARCHAR and NVARCHAR and enforce EF to throw some sort of type mismatch exception during SaveChanges? I've tried to use this in my configuration class:
Property(e => e.Bar).IsUnicode(true);
Property(e => e.Bar).HasColumnType("NVARCHAR(MAX)");
but it did nothing.
Thanks in advance.

The default data type for string columns is nvarchar(MAX), you don't have the need to set data type in your columns for changing to NVARCHAR(MAX). Ef has default conventions that Specify it. here is explained for knowing conventions.
if you want config generally convention for your models, you can do this:
public class DataTypeConvention : Convention
{
public DataTypeConvention()
{
Properties<string>().Configure(config => { config.HasColumnType("nvarchar(MAX)"); });
}
}
on your DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new DataTypeConvention());
}

Related

How can I use SumAsync to calculate sum of a customized value object in Asp.Net core

I have a Model with a property of a value object type as following:
public class Course : AggregateRoot, ISpModel
{
...
public UnsignedNumber MaximumCapacity { get; private set; }
...
}
with UnsignedNumber being a value object containing a short value:
public class UnsignedNumber : BaseValueObject<UnsignedNumber>
{
public short Value { get; }
...
}
What I need to do is to sum all the MaximumCapacities of courses which correspond with certain conditions, but when I try to add a SumAsync(x => x.MaximumCapacity) at the end of the query, I get a syntax error
the syntax error
and when I try to do the same with it's value, I get a linq error in runtime.
"The LINQ expression '(int)(EntityShaperExpression: \r\n EntityType: Course\r\n ValueBufferExpression: \r\n (ProjectionBindingExpression: Outer)\r\n IsNullable: False\r\n).MaximumCapacity.Value' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."
Edit:
Here's the Linq Expression that encounters the problem:
var query = _dbContext.Courses.AsQueryable();
query = query.Include(x => BunchOfIncludes(x));
var res = await query.Where(x => BunchOfClauses(x)).SumAsync(x => x.MaximumCapacity.Value);
Edit2: the classes mentioned above:
public abstract class AggregateRoot : Entity
{
private readonly List<IDomainEvent> _events;
protected AggregateRoot() => _events = new List<IDomainEvent>();
public AggregateRoot(IEnumerable<IDomainEvent> events)
{
if (events == null) return;
foreach (var #event in events)
((dynamic)this).On((dynamic)#event);
}
protected void AddEvent(IDomainEvent #event) => _events.Add(#event);
public IEnumerable<IDomainEvent> GetEvents() => _events.AsEnumerable();
public void ClearEvents() => _events.Clear();
}
public interface ISpModel
{
}
public abstract class BaseValueObject<TValueObject> : IEquatable<TValueObject>
where TValueObject : BaseValueObject<TValueObject>
{
...
public static bool operator ==(BaseValueObject<TValueObject> right, BaseValueObject<TValueObject> left)
{
if (right is null && left is null)
return true;
if (right is null || left is null)
return false;
return right.Equals(left);
}
...
}

How to automap a collection of components with Fluent NHibernate?

All of my entities and value objects implement marker interfaces IEntity and IValueObject. I have set them up to be treated as components like so:
public override bool IsComponent(Type type)
{
return typeof(IValueObject).IsAssignableFrom(type);
}
public override bool ShouldMap(Type type)
{
return typeof(IEntity).IsAssignableFrom(type) || typeof(IValueObject).IsAssignableFrom(type);
}
Unfortunately, this does not seem to allow entities that have collections of value objects to be automapped as component collections. For example:
public class MyEntity : IEntity
{
public IList<MyValueObject> Objects { get; set; }
}
public class MyValueObject : IValueObject
{
public string Name { get; set; }
public string Value { get; set; }
}
Is there any way to define a convention such that, any time an IEntity has an IList of a type that implements IValueObject, it gets mapped as if I had specified:
HasMany(x => x.Objects)
.Component(x => {
x.Map(m => m.Name);
x.Map(m => m.Value);
});
What I don't want to do is have to manually do these overrides for every class and write out each property for the value object again and again.
Create a new class that inherits from HasManyStep (FluentNHibernate.Automapping.Steps).
Override the ShouldMap() method with something like :
return base.ShouldMap(member) && IsCollectionOfComponents(member)
Add your logic to :
public void Map(ClassMappingBase classMap, Member member)
{ ... }
Replace the default step with your new one :
public class MyMappingConfiguration : DefaultAutomappingConfiguration
{
public override IEnumerable<IAutomappingStep> GetMappingSteps(AutoMapper mapper, IConventionFinder conventionFinder)
{
var steps = base.GetMappingSteps(mapper, conventionFinder);
var finalSteps = steps.Where(c => c.GetType() != typeof(FluentNHibernate.Automapping.Steps.HasManyToManyStep)).ToList();
var idx = finalSteps.IndexOf(steps.Where(c => c.GetType() == typeof(PropertyStep)).First());
finalSteps.Insert(idx + 1, new MyCustomHasManyStep(this));
return finalSteps;
}
}
Note : You could also get the original source code of HasManyStep.cs and copy it to your project to introduce your custom logic.

Context variables in Ninject 2

I found this article on Context Variables in an earlier version of Ninject. My question is two-fold. First, how can I get this behavior with Ninject 2? Secondly, do context variables carry through down the request chain? For example, let's say I wanted to replace these calls:
var a = new A(new B(new C())));
var specialA = new A(new B(new SpecialC()));
... with this:
var a = kernel.Get<A>();
var specialA = kernel.Get<A>(With.Parameters.ContextVariable("special", "true"));
Is it possible to set up a binding like this, where the context remembers that it is in a "special" context when it comes time to construct a C?
Here's some stuff that I use against V2, with ~0 effort to clean it up for you - let me know if you can't disentagle it.
As you surmised, there doesn't seem to be a really explicit API that surfaces the "context parameter, even for nested resolutions" stuff in v2 as-is (it's presence is buried as the 3rd parameter on an overload of the Parameter ctor).
public static class ContextParameter
{
public static Parameter Create<T>( T value )
{
return new Parameter( value.GetType().FullName, value, true );
}
}
public static class ContextParameterFacts
{
public class ProductId
{
public ProductId( string productId2 )
{
Value = productId2;
}
public string Value { get; set; }
}
public class Repository
{
public Repository( ProductId productId )
{
ProductId = productId;
}
public ProductId ProductId { get; set; }
}
public class Outer
{
public Outer( Repository repository )
{
Repository = repository;
}
public Repository Repository { get; set; }
}
public class Module : NinjectModule
{
public override void Load()
{
Bind<ProductId>().ToContextParameter();
}
}
//[ Fact ]
public static void TwoDeepShouldResolve()
{
var k = new StandardKernel( new Module() );
var o = k.Get<Outer>( ContextParameter.Create( new ProductId( "a" ) ) );
Debug.Assert( "a" == o.Repository.ProductId.Value );
}
}
And here's some code [that'll confuse the matter] which demonstrates how I apply it in my context:-
public class ServicesNinjectModule : NinjectModule
{
public override void Load()
{
Bind<ProductId>().ToContextParameter();
Bind<Func<ProductId, ResourceAllocator>>().ToConstant( ( productId ) => Kernel.Get<ResourceAllocator>(
ContextParameter.Create( productId ) ) );
}
}
public static class NinjectContextParameterExtensions
{
public static IBindingWhenInNamedWithOrOnSyntax<T> ToContextParameter<T>( this IBindingToSyntax<T> bindingToSyntax )
{
return bindingToSyntax.ToMethod( context => (T)context.Parameters.Single( parameter => parameter.Name == typeof( T ).FullName ).GetValue( context ) );
}
}
As usual, you should go look a the source and the tests - they'll provide you with a far more detailed and relevant answer than I can.

Fluent nHibernate Automapping not creating Plural table name

I have two tables, Locations and Facilities
They map to two classes,
public Location : Entity
{
//properties
}
public Facility : Entity
{
public virtual Location Location { get; set; }
}
Everything works just dandy, until I change facility to this
public Facility : Location
{
}
Now I get an exception from nHibernate saying
NHibernate.ADOException was unhandled by user code
Message=could not execute query
InnerException: System.Data.SqlClient.SqlException
Message=Invalid object name 'Facility'.
For some reason it is not creating the plural name of the table into the sql string.
Thanks for any help!
EDIT
This is my current TableNameConvention
public class TableNameConvention : IClassConvention
{
public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
{
instance.Table(Inflector.Net.Inflector.Pluralize(instance.EntityType.Name));
}
}
When Facility inherits from Entity, the Facility does run through this method. When it inherits from Location, it does not
Edit 2
Figured I'd post everything...
public class AutoPersistenceModelGenerator : IAutoPersistenceModelGenerator
{
#region IAutoPersistenceModelGenerator Members
public AutoPersistenceModel Generate()
{
var mappings = new AutoPersistenceModel();
mappings.AddEntityAssembly(typeof(Person).Assembly).Where(GetAutoMappingFilter);
mappings.Conventions.Setup(GetConventions());
mappings.Setup(GetSetup());
mappings.IgnoreBase<Entity>();
mappings.IgnoreBase(typeof(EntityWithTypedId<>));
mappings.UseOverridesFromAssemblyOf<AutoPersistenceModelGenerator>();
return mappings;
}
#endregion
private Action<AutoMappingExpressions> GetSetup()
{
return c =>
{
c.FindIdentity = type => type.Name == "Id";
};
}
private Action<IConventionFinder> GetConventions()
{
return c =>
{
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.ForeignKeyConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.HasManyConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.HasManyToManyConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.ManyToManyTableNameConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.PrimaryKeyConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.ReferenceConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.TableNameConvention>();
};
}
/// <summary>
/// Provides a filter for only including types which inherit from the IEntityWithTypedId interface.
/// </summary>
private bool GetAutoMappingFilter(Type t)
{
return t.GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
}
}
Have you set a convention?
public class TableNameConvention : IClassConvention
{
public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
{
string typeName = instance.EntityType.Name;
instance.Table(Inflector.Net.Inflector.Pluralize(typeName));
}
}
This is an old question, but for the sake of others who stumble upon this looking for an answer, you can also create a convention that uses the built-in PluralizationService that comes with EF:
public class TableNameConvention : IClassConvention
{
public void Apply(IClassInstance instance)
{
string typeName = instance.EntityType.Name;
instance.Table(PluralizationService.CreateService(CultureInfo.CurrentCulture).Pluralize(typeName));
}
}

AutoMapper map IdPost to Post

I'm trying to map int IdPost on DTO to Post object on Blog object, based on a rule.
I would like to achieve this: BlogDTO.IdPost => Blog.Post
Post would be loaded by NHibernate: Session.Load(IdPost)
How can I achieve this with AutoMapper?
You could define AfterMap action to load entities using NHibernate in your mapping definition. I'm using something like this for simmilar purpose:
mapperConfiguration.CreateMap<DealerDTO, Model.Entities.Dealer.Dealer>()
.AfterMap((src, dst) =>
{
if (src.DepartmentId > 0)
dst.Department = nhContext.CurrentSession.Load<CompanyDepartment>(src.DepartmentId);
if (src.RankId > 0)
dst.Rank = nhContext.CurrentSession.Load<DealerRank>(src.RankId);
if (src.RegionId > 0)
dst.Region = nhContext.CurrentSession.Load<Region>(src.RegionId);
});
you can do this easily with the ValueInjecter
it would be something like this:
//first you need to create a ValueInjection for your scenario
public class IntToPost : LoopValueInjection<int, Post>
{
protected override Post SetValue(int sourcePropertyValue)
{
return Session.Load(sourcePropertyValue);
}
}
// and use it like this
post.InjectFrom(new IntToPost().SourcePrefix("Id"), postDto);
also if you always have the prefix Id than you could set it in the constructor of the IntToPost
and use it like this:
post.InjectFrom<IntToPost>(postDto);
Create a new Id2EntityConverter
public class Id2EntityConverter<TEntity> : ITypeConverter<int, TEntity> where TEntity : EntityBase
{
public Id2EntityConverter()
{
Repository = ObjectFactory.GetInstance<Repository<TEntity>>();
}
private IRepository<TEntity> Repository { get; set; }
public TEntity ConvertToEntity(int id)
{
var toReturn = Repository.Get(id);
return toReturn;
}
#region Implementation of ITypeConverter<int,TEntity>
public TEntity Convert(ResolutionContext context)
{
return ConvertToEntity((int)context.SourceValue);
}
#endregion
}
Configure AM to auto create maps for each type
public class AutoMapperGlobalConfiguration : IGlobalConfiguration
{
private AutoMapper.IConfiguration _configuration;
public AutoMapperGlobalConfiguration(IConfiguration configuration)
{
_configuration = configuration;
}
public void Configure()
{
//add all defined profiles
var query = this.GetType().Assembly.GetExportedTypes()
.Where(x => x.CanBeCastTo(typeof(AutoMapper.Profile)));
_configuration.RecognizePostfixes("Id");
foreach (Type type in query)
{
_configuration.AddProfile(ObjectFactory.GetInstance(type).As<Profile>());
}
//create maps for all Id2Entity converters
MapAllEntities(_configuration);
Mapper.AssertConfigurationIsValid();
}
private static void MapAllEntities(IProfileExpression configuration)
{
//get all types from the my assembly and create maps that
//convert int -> instance of the type using Id2EntityConverter
var openType = typeof(Id2EntityConverter<>);
var idType = typeof(int);
var persistentEntties = typeof(MYTYPE_FROM_MY_ASSEMBLY).Assembly.GetTypes()
.Where(t => typeof(EntityBase).IsAssignableFrom(t))
.Select(t => new
{
EntityType = t,
ConverterType = openType.MakeGenericType(t)
});
foreach (var e in persistentEntties)
{
var map = configuration.CreateMap(idType, e.EntityType);
map.ConvertUsing(e.ConverterType);
}
}
}
Pay attention to MapAllEntities method. That one will scan all types and create maps on the fly from integer to any type that is of EntityBase (which in our case is any persistent type).
RecognizePostfix("Id") in your case might be replace with RecognizePrefix("Id")