How do I include a [NotMapped] property in an EF business object without getting FirstChance IndexOutofRangeException? - entity-framework-6

I was wondering why my XAF WinForms EF application was slow loading a detail view.
Then I learned how to capture FirstChance Exceptions and discovered I was experiencing an IndexOutOfRange exception as described here
Sometimes I want to include a non mapped property in my business object such as Job in example.
public class OrderLineResult
{
public int LineId { get; set; }
public int Quantity { get; set; }
public string Description { get; set; }
[Browsable(false)] public int JobId { get; set; }
[NotMapped] [Browsable(false)] public virtual Job Job { get; set; }
}
And I have a method to get the data inside the OrderLineResult class
public static OrderLineResult[] GetData(int headId)
{
using var connect = new MyDbContext()
const string sql =
#"SET NOCOUNT ON;
create table #temp( JobId int, Quantity int, LineId int, Description )
/* code to populate the table */
select JobId,LineId,Quantity, Description from #temp"
var results = connect.Database.SqlQuery<OrderLineResult>(sql,headId).ToArray();
return results.ToArray();
}
}
Yet the IndexOutOfRange exception occurs for the Job property.
The call stack is
System.IndexOutOfRangeException
Job
at MyApp.Module.Win.Controllers.ToDoList.TaskActionController.<>c.<actExceptions_Execute>b__34_0(Object sender, FirstChanceExceptionEventArgs e)
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.TryGetColumnOrdinalFromReader(DbDataReader storeDataReader, String columnName, Int32& ordinal)
at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.CreateColumnMapFromReaderAndClrType(DbDataReader reader, Type type, MetadataWorkspace workspace)
at System.Data.Entity.Core.Objects.ObjectContext.InternalTranslate[TElement](DbDataReader reader, String entitySetName, MergeOption mergeOption, Boolean streaming, EntitySet& entitySet, TypeUsage& edmType)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass186_0`1.<ExecuteStoreQueryReliably>b__1()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass186_0`1.<ExecuteStoreQueryReliably>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at MyApp.Module.BusinessObjects.NonPersistedBusinessObjects.OrderLineResult.GetData(Int32 headId)
I am using EntityFramework 6.4.4 and .Net Framework 4.7.2

This feels like a cludge,
I added
,null as job
to the last select statement

Related

MVC project No parameterless constructor defined for this object

im getting this error. Im newbie on MVC .
Can you help me please.I found somethings but i didnt understand what i will do. Sorry for my english.
I have 4 projects in a solution
.Admin
.UI
.Core
.Data
I have a problem with admin side.
Im trying to LoginFilter in admin page. When i run the project the page forwarding to /Account/Login page but its giving this error.
Error Page:
No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +206
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +11
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a controller of type 'WebHaber.Admin.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +76
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +88
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +194
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1098.0
AccountController.cs
using WebHaber.Core.Infrastructure;
using WebHaber.Data.Model;
namespace WebHaber.Admin.Controllers
{
public class AccountController : Controller
{
#region Kullanıcı
private readonly IKullaniciRepository _kullaniciRepository;
public AccountController(IKullaniciRepository kullaniciRepository)
{
_kullaniciRepository = kullaniciRepository;
}
#endregion
// GET: Account
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Kullanici kullanici)
{
var KullaniciVarmi = _kullaniciRepository.GetMany(x => x.Email == kullanici.Email && x.Sifre == kullanici.Sifre && x.Aktif == true).SingleOrDefault();
if (KullaniciVarmi != null)
{
if (KullaniciVarmi.Rol.RolAdi == "Admin")
{
Session["KullaniciEmail"] = KullaniciVarmi.Email;
return RedirectToAction("Index", "Home");
}
ViewBag.Mesaj = "Yetkisiz Kullanıcı";
return View();
}
ViewBag.Mesaj = "Kullanıcı Bulunamadı";
return View();
}
LoginFilter.cs
namespace WebHaber.Admin.CustomFilter
{
public class LoginFilter : FilterAttribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
HttpContextWrapper wrapper = new HttpContextWrapper(HttpContext.Current);
var SessionControl = context.HttpContext.Session["KullaniciEmail"];
if (SessionControl == null)
{
context.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "Controller", "Account" }, { "action", "Login" } });
}
}
public void OnActionExecuting(ActionExecutingContext context)
{}
BootStrapper.cs
using Autofac;
using Autofac.Integration.Mvc;
using WebHaber.Core.Infrastructure;
using WebHaber.Core.Repository;
using WebHaber.Data.DataContext;
namespace WebHaber.Admin.Class
{
public class BootStrapper
{
//Boot aşamasında çalışacak.
public static void RunConfig()
{
BuilAutoFac();
}
private static void BuilAutoFac()
{
var builder = new ContainerBuilder();
builder.RegisterType<HaberRepository>().As<IHaberRepository>();
builder.RegisterType<ResimRepository>().As<IResimRepository>();
builder.RegisterType<KullaniciRepository>().As<IKullaniciRepository>();
builder.RegisterType<RolRepository>().As<IRolRepository>();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
Global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BootStrapper.RunConfig();
}
}
KullaniciRepository.cs
namespace WebHaber.Core.Repository
{
public class KullaniciRepository : IKullaniciRepository
{
private readonly HaberContext _context = new HaberContext();
public IEnumerable<Kullanici> GetAll()
{
//Tüm haberler dönecek
return _context.Kullanici.Select(x => x);
}
public Kullanici GetByID(int id)
{
return _context.Kullanici.FirstOrDefault(x => x.ID == id);
}
public Kullanici Get(Expression<Func<Kullanici, bool>> expression)
{
return _context.Kullanici.FirstOrDefault(expression);
}
public IQueryable<Kullanici> GetMany(Expression<Func<Kullanici, bool>> expression)
{
return _context.Kullanici.Where(expression);
}
public void Insert(Kullanici obj)
{
_context.Kullanici.Add(obj);
}
public void Update(Kullanici obj)
{
_context.Kullanici.AddOrUpdate();
}
public void Delete(int id)
{
var kullanici = GetByID(id);
if (kullanici!= null)
{
_context.Kullanici.Remove(kullanici);
}
}
public int Count()
{
return _context.Kullanici.Count();
}
public void Save()
{
_context.SaveChanges();
}
}
}
IKullaniciRepository.cs
namespace WebHaber.Core.Infrastructure
{
public interface IKullaniciRepository : IRepository<Kullanici>
{
}
}
IRepository.cs
namespace WebHaber.Core.Infrastructure
{
public interface IRepository<T> where T: class
{
IEnumerable<T> GetAll();
T GetByID(int id);
T Get(Expression<Func<T, bool>> expression);
IQueryable<T> GetMany(Expression<Func<T, bool>> expression);
void Insert(T obj);
void Update(T obj);
void Delete(int id);
int Count();
void Save();
}
}
Kullanici.cs model
namespace WebHaber.Data.Model
{
[Table("Kullanici")]
public class Kullanici
{
public int ID { get; set; }
[Display(Name = "Ad Soyad")]
[MaxLength(150, ErrorMessage = "150 karakterden fazla girildi.")]
[Required]
public string AdSoyad { get; set; }
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
[Required]
public string Email { get; set; }
public string KullaniciAdi { get; set; }
[Display(Name = "Şifre")]
[DataType(DataType.Password)]
[Required]
public string Sifre { get; set; }
..............
..............
.............
The issue is pretty straightforward — An error occurred when trying to create a controller of type 'WebHaber.Admin.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.
You're trying to use Autofac to inject IKullaniciRepository service into the AccountController but the compiler couldn't find one although you've the declared the service registration at BootStrapper.cs
Therefore it's likely that BootStrapper.cs's RunConfig never get invoked. Just place a call (e.g. BootStrapper.RunConfig()) to Application_Start() method in Global.asax and you're fine.
#Zephyr thank you for help.
I added new global.asax file.
Because my Application_Start() was not firing.
In global.asax
Old one :
public class MvcApplication : System.Web.HttpApplication
new one: `
public class Global : System.Web.HttpApplication`

IdentityRole Navigational Property Exception Using Entity Framework

I am having an issue mapping the "IdentityRole" property to my ApplicationUsers class. I am receiving an error to the effect of:
++++
The declared type of navigation property WebApp.Core.DAL.ApplicationUsers.IdentityRoles is not compatible with the result of the specified navigation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.Entity.Core.MetadataException: The declared type of navigation property WebApp.Core.DAL.ApplicationUsers.IdentityRoles is not compatible with the result of the specified navigation.
Source Error:
Line 28: using (CMSContext cntx = new CMSContext())
Line 29: {
Line 30: var users = cntx.Users
Line 31: .Include(m => m.IdentityRoles)
Line 32: .Include(s => s.AspNetUsersSites)
Source File: c:\LocalSites\WebApp\1.0.0.0\DAL\UserManagement\User.cs Line: 30
Stack Trace:
[MetadataException: The declared type of navigation property WebApp.Core.DAL.ApplicationUsers.IdentityRoles is not compatible with the result of the specified navigation. ]
System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.ValidateNavPropertyOp(PropertyOp op) +401
System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(PropertyOp op, Node n) +80
System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) +163
System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.VisitScalarOpDefault(ScalarOp op, Node n) +33
System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) +163
System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n) +22
System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitAncillaryOpDefault(AncillaryOp op, Node n) +21
System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) +163
System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n) +22
System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitAncillaryOpDefault(AncillaryOp op, Node n) +21
System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) +163
System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n) +38
System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op, Node n) +599
System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) +163
System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n) +22
System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitPhysicalOpDefault(PhysicalOp op, Node n) +21
System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(Dictionary`2& tvfResultKeys) +106
System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(PlanCompiler planCompilerState, StructuredTypeInfo& typeInfo, Dictionary`2& tvfResultKeys) +54
System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler.Compile(List`1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set`1& entitySets) +236
System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory) +441
++++
I have lazy loading off and my ApplicationUsers class looks like this
namespace WebApp.Core.Contracts
{
public class ApplicationUsers : IdentityUser
{
public bool IsActive { get; set; }
public string LockoutReason { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Photo { get; set; }
public virtual List<AspNetUsersSites> AspNetUsersSites { get; set; }
// a collection of roles that can be written to, since it needs to be evaluated earlier before it's disposed of
[ForeignKey("Id")]
public virtual List<IdentityRole> IdentityRoles { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUsers> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public async Task<IList<string>> GenerateUserRolesAsync(UserManager<ApplicationUsers> manager, string userId)
{
var userRoles = await manager.GetRolesAsync(this.Id);
return userRoles;
}
public async Task DeleteUser(UserManager<ApplicationUsers> manager, string username)
{
var user = manager.FindByName(username);
await manager.DeleteAsync(user);
}
}
My Linq query looks like this
public static List<Contracts.ApplicationUsers> GetUsersForSiteWithRoles(int SiteID){
using (CMSContext cntx = new CMSContext())
{
var users = cntx.Users
.Include(m => m.IdentityRoles)
.Include(s => s.AspNetUsersSites)
.Where(i => i.AspNetUsersSites.Where(s => s.SiteID == SiteID).Count() > 0).ToList();
return users;
}
}
What is wrong with the navigational property I added and/or the query. All I am really trying to do is return users with their roles that are stored in my database.
Thank you!
First, it should be:
public virtual ICollection<IdentityRole> IdentityRoles { get; set; }
Not List<IdentityRole>.
Second, this relationship already exists on ApplicationUser through inheritance from IdentityUser in the Roles property. You're creating a secondary relationship here that will never be used by the Identity framework.
Also, for what it's worth, if you want your AspNetUserSites to follow the table name scheme of the Identity tables, you need only specify the Table attribute on the class. Naming your class in this way is obtuse. For example:
[Table("AspNetUserSites")]
public class Site
{
...
}
Then you just have a nice class like Site instead of AspNetUserSite
UPDATE
IdentityUserRole is just the join table between IdentityUser and IdentityRole. In the default implementation there's not a whole lot of point in its existence, but you could potentially extend the Identity classes to attach additional information on the relationship that way.
Anyways, if you just want to get at the actual IdentityRoles, just do something like:
var roleIds = user.Roles.Select(r => r.RoleId).ToList();
var roleNames = db.Roles.Where(r => roleIds.Contains(r.Id)).Select(r => r.Name);

Code first Migrations with IdentityUser gives an error

I'm trying to use Code First Migrations with IdentityUser.
Here's my dbContext
public class JbDb : IdentityDbContext<User>
{
public JbDb()
: base(ConfigurationManager.ConnectionStrings["JbDb"].ConnectionString)
{
}
public IDbSet<User> User { get; set; }
public virtual IDbSet<T> DbSet<T>() where T : class
{
return Set<T>();
}
public virtual void Commit()
{
base.SaveChanges();
}
}
internal class Initialiser : CreateDatabaseIfNotExists<JbDb>
{
protected override void Seed(JbDb context)
{
context.SaveChanges();
}
}
Here's the code for User model
[Table("User", Schema = "Security")]
public class User:IdentityUser
{
public string UserId
{
get { return Id; }
}
public string Email { get; set; }
public bool IsEmailVerified { get; set; }
public bool IsDeleted { get; set; }
}
Connection String is like this:
<add name="JbDb" connectionString="Data Source=CENLP\HRMSQL;Initial Catalog=JbDb;Integrated Security=True" providerName="System.Data.SqlClient" />
but when i'm trying to enable the migrations, it gives an error saying
Checking if the context targets an existing database... System.InvalidOperationException: Multiple object sets per type are
not supported. The object sets 'User' and 'Users' can both contain
instances of type 'Jb.Model.Security.User'. at
System.Data.Entity.Internal.DbSetDiscoveryService.RegisterSets(DbModelBuilder
modelBuilder) at
System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext
internalContext) at
System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) at
System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at
System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps()
at System.Data.Entity.Database.Exists() at
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext1.IsIdentityV1Schema(DbContext
db) at
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext1..ctor(String
nameOrConnectionString, Boolean throwIfV1Schema) at
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext1..ctor(String
nameOrConnectionString) at Jb.DataAccess.JbDb..ctor() in
d:\CENT-Jb\Jb\Jb.DataAccess\JbDb.cs:line 10
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Data.Entity.Infrastructure.DbContextInfo.CreateInstance() at
System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type
contextType, DbProviderInfo modelProviderInfo, AppConfig config,
DbConnectionInfo connectionInfo, Func`1 resolver) at
System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
configuration, DbContext usersContext, DatabaseExistenceState
existenceState) at
System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
configuration) at
System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration
migrationsConfiguration) at
System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate
callBackDelegate) at
System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
runner) at
System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldInitialCreate(String
language, String rootNamespace) at
System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
at
System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action
command) Multiple object sets per type are not supported. The object
sets 'User' and 'Users' can both contain instances of type
'Jb.Model.Security.User'..
It will be really helpful if one can point me out what is wrong here
[Table("Users", Schema = "Security")]

nhibernate HQL select from two or multiple tables

I have been trying to get results using HQL for two classes. It works for one table but does not work for two tables.
The two entities below;
public class A_CUSTOMER
{
public virtual string CUSTOMER_NO { get; set; }
public virtual string ADDRESS_LINE { get; set; }
public virtual IList<A_ACCOUNT> ACCOUNTS { get; set; }
}
public class A_ACCOUNT
{
public virtual string AC_NO { get; set; }
public virtual string CUST_NO { get; set; }
public virtual string CCY { get; set; }
public virtual string AVL_BAL { get; set; }
public virtual A_CUSTOMER CUSTOMER { get; set; }
}
Mappings for the classes below;
public class A_CUSTOMERMap:ClassMap<A_CUSTOMER>
{
public A_CUSTOMERMap()
{
Id(x => x.CUSTOMER_NO);
Map(x => x.ADDRESS_LINE);
HasMany(x => x.ACCOUNTS).KeyColumns.Add("CUST_NO");
}
}
public class A_CUST_ACCOUNTMap:ClassMap<A_CUST_ACCOUNT>
{
public A_CUST_ACCOUNTMap()
{
Id(x => x.AC_NO);
Map(x=>x.CUST_NO);
Map(x => x.AVL_BAL);
Map(x => x.CCY);
References(x => x.CUSTOMER,"CUST_NO");
}
}
Now, I have a code like this in my controller:
string myString = "1001,1002,1003,1004,1005";
var indNumbers = myString.Split(',');
string qry = #"select h.AC_NO,h.BRANCH_CODE,h.CUST_NO,h.CCY,h.AVL_BAL ,g.ADDRESS_LINE"+
"from A_ACCOUNT as h,A_CUSTOMER g "+
"where h.CUST_NO=g.CUSTOMER_NO AND h.AC_NO IN (:list)";
;
res = session.CreateQuery(qry)
.SetParameterList("list", indNumbers)
.List();
I have also tried different query string:
string qry = #"select h.AC_NO,h.BRANCH_CODE,h.CUST_NO,h.CCY,h.AVL_BAL ,g.ADDRESS_LINE"+
"from A_ACCOUNT as h left join A_CUSTOMER g on "+
"h.CUST_NO=g.CUSTOMER_NO"+
"where h.AC_NO IN (:list)";
The error encountered below, any help will be much appreciated.
NHibernate.Hql.Ast.ANTLR.QuerySyntaxException was unhandled by user code
HResult=-2146232832
Message=Exception of type 'Antlr.Runtime.NoViableAltException' was thrown. near line 1, column 83
Source=NHibernate
StackTrace:
at NHibernate.Hql.Ast.ANTLR.ErrorCounter.ThrowQueryException()
at NHibernate.Hql.Ast.ANTLR.HqlParseEngine.Parse()
at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryString, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.HQLStringQueryPlan.CreateTranslators(String hql, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.HQLStringQueryPlan..ctor(String hql, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.HQLStringQueryPlan..ctor(String hql, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(String queryString, Boolean shallow, IDictionary`2 enabledFilters)
at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(String query, Boolean shallow)
at NHibernate.Impl.AbstractSessionImpl.CreateQuery(String queryString)
at MvcApplication2.Controllers.CustAccountController.GetCustData(jQueryDataTableParamModel param) in ...
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException:
You are missing spaces after the word ADDRESS_LINE and before the second line from
string qry = #"select h.AC_NO,h.BRANCH_CODE,h.CUST_NO,h.CCY,h.AVL_BAL ,g.ADDRESS_LINE"+
"from A_ACCOUNT as h,A_CUSTOMER g "+
"where h.CUST_NO=g.CUSTOMER_NO AND h.AC_NO IN (:list)";
One way to rerite this is to drop all occurrences of quotes:- " + " e.g.
var qry = #"select h.AC_NO,h.BRANCH_CODE,h.CUST_NO,h.CCY,h.AVL_BAL ,g.ADDRESS_LINE
from A_ACCOUNT as h,A_CUSTOMER g
where h.CUST_NO=g.CUSTOMER_NO AND h.AC_NO IN (:list)";
Notice in my sample I only have a started " (quote) and an ending ".
Rippo was right about the spacing and quotes, in addition i noticed i was still referring to the Class names in HQL instead of the alias Reference names
I changed from
"A_ACCOUNT as h left join A_CUSTOMER g on "
to
"from A_ACCOUNT as h left join h.CUSTOMER g on "
It should have been
string qry = #"select h.AC_NO,h.BRANCH_CODE,h.CUST_NO,h.CCY,h.AVL_BAL ,g.ADDRESS_LINE"+
"from A_ACCOUNT as h left join h.CUSTOMER g on "+
"h.CUST_NO=g.CUSTOMER_NO"+
"where h.AC_NO IN (:list)";

Entity Framework doesn't create Database

i'm creating a database with entity framework, in an mvc asp.net application, using code first.
I'm new to the argument so be patient... I've created the database for the first time and all seems to be right; but couse of i didn't create a DropCreateDatabaseIfModelChanges method to change the tables i decided to manually delete the database.
The problem is that the database is not recreating!
I've implemented the initializer and it is in a different class from the context...
public class WidgetDbInitializer : DropCreateDatabaseIfModelChanges<WidgetDbContext>
{
}
Setted it up in Global.asax.cs and forced to init that
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer<Portale.Models.WidgetDbContext>(new Portale.Models.WidgetDbInitializer());
var _initer = new WidgetDbInitializer();
using (var db = new WidgetDbContext())
{
_initer.Seedit(db);
db.Database.Initialize(true);
}
}
I've just the default connection string couse now i don't care about it...
Please help me i've read tons of articles over the web and i can't get a solution...
The error i get:
System.ArgumentNullException non è stata gestita dal codice utente
Message=Il valore non può essere null.
Nome parametro: key
Source=mscorlib
ParamName=key
StackTrace:
in System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
in System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.SortedEntityTypeIndex.Add(EdmEntitySet entitySet, EdmEntityType entityType)
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Analyze()
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Configure()
in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
in System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
in System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
in System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
in System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
in System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
in System.Data.Entity.Internal.InternalContext.Initialize()
in System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
in System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
in System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
in System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
in System.Linq.Queryable.Join[TOuter,TInner,TKey,TResult](IQueryable`1 outer, IEnumerable`1 inner, Expression`1 outerKeySelector, Expression`1 innerKeySelector, Expression`1 resultSelector)
in Portale.Controllers.WidgetContainerController.Index() in C:\Users\doompro\Documents\Visual Studio 2010\Projects\Portale\Portale\Controllers\WidgetContainerController.cs:riga 56
in lambda_method(Closure , ControllerBase , Object[] )
in System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
in System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
in System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
override Seed function in your WidgetDbInitializer class and try to add some data to your database .
protected override void Seed(WidgetDbContext context)
{
context.yourodel.add(new class() )
}
first check your overriden seed invoke correctly , then if your database dose not generated you will get an exception .
Solved the problem:
public class Widget
{
//This properties rapresent the primary key for entity framework
[Key]
public int WidgetID { get; set; }
//Foreing key to the column where this widget is stored
public virtual int ColumnID { get; set; }
//The title of the widget
public string Title { get; set; }
//Controller of the Widget, this property may be used on the RenderAction call
public string Controller { get; set; }
//ActionMethod of the Widget, this property may be used on the RenderAction call
public string ActionMethod { get; set; }
//The Type of the Model, used on deserialization
public Type ModelType { get; set; }
//The context of the widget
public string SerializedModel { get; set; }
}
The database just didn't accept the type "Type", all working fine as soon as I deleted that field... I just didn't look at it because it was working with the "Object" type, didn't expect it doesnt with Type..

Resources