C# Entity Framework Commit Error - c#

I have a weird error when trying to call .SaveChanges() in Entity Framework.
I'm trying to save an Order like this
public void SaveOrder(UserDTO user, ArticleDTO article, PriceDTO price, decimal amount)
{
//Get the order with type cart. If no order exist create a new order with type cart.
var order = _orderRepository.GetCartOrderForCustomer(user.Customer.CustomerREFID);
if (order == null)
{
order = new Order()
{
CustomerREFID = user.Customer.CustomerREFID,
CreateDate = DateTime.Now,
OrderType = OrderType.Cart
};
_orderRepository.Add(order);
_orderRepository.UnitOfWork.Commit();
}
}
Sure its working fine when I'm only calling this method. But when I'm calling another method before this method then I get errors.
The before method just fetch articles and prices.
public IEnumerable<Article> GetArticlesByCategory(int categorySection, int headCategory, string customerREFID)
{
var currentUnitOfWork = this.UnitOfWork as MainBCUnitOfWork;
//Linq query without keys.
var result = (from a in currentUnitOfWork.Articles
join cat in currentUnitOfWork.Categories on a.CategoryID equals cat.CategoryID
join cf in currentUnitOfWork.CategoryReferences on cat.ID equals cf.CategoryID
join c in currentUnitOfWork.Customers on a.Lagstalle equals c.LagStalle
where cf.RefID == categorySection && cat.HuvudKat == headCategory && c.CustomerREFID == customerREFID
select a).ToList();
var artnumbers = result.Select(a => a.Number).ToList();
var prices = currentUnitOfWork.Prices.Where(p => artnumbers.Contains(p.ArtNr) && p.FtgNr == customerREFID).ToList();
Parallel.ForEach(result, a =>
{
a.Prices = prices.Where(p => p.ArtNr == a.Number).ToList();
});
return result.ToList();
}
So when calling SaveOrder I get this error :
{System.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_dbo.PriceArticles'. Cannot insert duplicate key in object 'dbo.PriceArticles'. The duplicate key value is (6653, 1).
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary2 identifierValues, List1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
ClientConnectionId:dfc62e28-3751-4a54-89f4-5fa8195cab2a}
This table and get has nothing to do with Order table ? Why does Entity Framework commit other tables when I only add a new Order ?
How do I work around this ?

Related

Getting error for HierarchyId while fetching the data from another server and inserting it into my server c#

Error is
The type of column 'MemberHId' is not supported. The type is 'SqlHierarchyId'.
In both the server the datatype is same "HierarchyId".
I am just using the ADO.Net.
The assembly is Microsoft.SqlServer.ManagedDTS version- 13.0.0.0
We are using Azure Sql.
Tried with different versions of sql assemblies
DataTable dt = new DataTable();
dt.Columns.Add("Code", typeof(string));
dt.Columns.Add("Description", typeof(string));
dt.Columns.Add("NodeId", typeof(int));
dt.Columns.Add("MemberHId", typeof(SqlHierarchyId));
dt.Columns.Add("Level", typeof(int));
//Getting the data from serverAPI which is returning the data in the columns without null records.
dt=apicall();
SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
cmd.Parameters.AddWithValue("#MemberH", dt);
cmd.CommandTimeout = 0;
cmd.Connection.Open();
cmd.ExecuteNonQuery();// Its failing here
My Sp consists of table type param #MemberHType and the procedure returns rows with these columns:
Name | Type
------------+----------
Code | varchar
Description | varchar
NodeID | smallint
MemberHId | hierarchyid
Level | smallint
This is the procedure:
alter PROCEDURE [dbo].[InsertHierarchyData]
(
#MemberHType MemberH READONLY
)
AS
truncate table test
BEGIN TRY
insert into test values ('start select')
--create table test (errormessage varchar(1000))
IF EXISTS (SELECT TOP 1 1 FROM #MemberHType)
BEGIN
insert into test values ('Inside first Insert start')
INSERT INTO HierarchyStaging
(
Code
,[Description]
,NodeID
,MemberhHId
,[Level]
)
SELECT
Code
,[Description]
,NodeId
,MemberhHId
,[Level]
FROM #MemberHType
insert into test values ('Inside first Insert end')
END
END TRY
BEGIN CATCH
SELECT #comment = ERROR_MESSAGE()
,#Status = 'Error'
SET #comment = CONVERT(NVARCHAR(3000),#Comment) + ' Error Severity: ' + CAST(ERROR_SEVERITY() AS varchar(25)) + ' Error state: 30'
GOTO ErrorHandler
END CATCH
The Column in c# is SqlHierarchyId.
Stack-trace:
at System.Data.SqlClient.TdsParser.TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc, Boolean sync, TaskCompletionSource`1 completion, Int32 startRpc, Int32 startParam)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
If I understand the documentation correctly, you can't use SqlHierarchyId as the data type of a DataColumn.
It doesn't appear in the System.Data.SqlTypes Namespace, and it also doesn't appear in the SQL Server Data Type Mappings table, which means there's no documented built in conversion between SQL Server's HierarchyId and a built in type in the .Net framework. (of course, undocumented features have been known to exist in SQL Server, but I wouldn't recommend relying on that).
What you can do, however, is to convert the HierarchyId to nvarchar using a simple cast in T-SQL when you read it into your c# application (which internally is calling the ToString() method):
CAST(MemberhHId AS nvarchar(4000)) as MemberHId
and convert it back using cast when you insert the data (which internally is calling the Parse() method):
CAST(MemberHId AS hierarchyid)

DatabaseGeneratedOption doesn't work in Dapper.FastCRUD

I setup my mapping like this:
[Table("Opportunity")]
public partial class Opportunity
{
// Other columns
...
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long OPPORTUNITY_ID { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public long? OPPORTUNITY_VALUE { get; set; }
// Other columns
...
}
My unit test is setup like this:
Opportunity opp = new Opportunity
{
DATE_CREATED_UTC = DateTime.UtcNow,
OWNER_USER_ID = TestConstants.USER_ID,
OPPORTUNITY_NAME = "unitTest-Opportunity",
PROBABILITY = 50,
BID_CURRENCY = "USD",
BID_AMOUNT = 6000,
BID_TYPE = "Fixed Bid",
OPPORTUNITY_STATE = "OPEN",
OPPORTUNITY_DETAILS = "UNIT TEST OPPORUNITY DETAIL",
VISIBLE_TO = "EVERYONE"
};
OppService.Add(opp);
Opportunity fromDB = OppService.Get(opp.OPPORTUNITY_ID);
OppService.Update(fromDB);
The last line would crash with the error: The column "OPPORTUNITY_VALUE" cannot be modified because it is either a computed column or is the result of a UNION operator.
What am I doing wrong? I am not modifying that column value at all. Here is the full error stack:
Result StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) in D:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 3397
at Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) in D:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 1346
at Dapper.FastCrud.SqlStatements.GenericSqlStatements`1.UpdateById(IDbConnection connection, TEntity keyEntity, ISqlStatementOptionsGetter statementOptions)
at Dapper.FastCrud.DapperExtensions.Update[TEntity](IDbConnection connection, TEntity entityToUpdate, Action`1 statementOptions)
at MyProject.Data.Repository`1.Update(T entity) in C:\MyFolder\Core\MyProject.Data\Repository.cs:line 80
at MyProject.Service.Base.ModelService`1.Update(T entity) in C:\MyFolder\Core\MyProject.Service\Base\ModelService.cs:line 38
at MyProject.Service.Base.InstanceEntityService`2.Update(T entity) in C:\MyFolder\Core\MyProject.Service\Base\InstanceEntityService.cs:line 72
at MyProject.Service.OpportunityService.Update(Opportunity entity) in C:\MyFolder\Core\MyProject.Service\OpportunityService.cs:line 21
at MyProject.Test.Service.OpportunityServiceTests.OpportunitiesCRUDTest() in C:\MyFolder\Test\Core\Service\OpportunityServiceTest.cs:line 22
Result Message: System.Data.SqlClient.SqlException : The column "OPPORTUNITY_VALUE" cannot be modified because it is either a computed column or is the result of a UNION operator.
CREATE statement for the table Opportunity:
CREATE TABLE [dbo].[Opportunity](
[OPPORTUNITY_ID] [bigint] IDENTITY(1,1) NOT NULL,
// Other columns
[BID_CURRENCY] [nvarchar](20) NULL,
[BID_AMOUNT] [bigint] NULL,
[BID_TYPE] [varchar](20) NULL,
[BID_DURATION] [int] NULL,
[OPPORTUNITY_VALUE] AS (case when [BID_TYPE]='Fixed Bid' AND [BID_AMOUNT] IS NOT NULL then [BID_AMOUNT] when [BID_TYPE]='Fixed Bid' AND [BID_AMOUNT] IS NULL then NULL when [BID_AMOUNT] IS NOT NULL AND [BID_DURATION] IS NOT NULL then [BID_AMOUNT]*[BID_DURATION] when [BID_DURATION] IS NULL then [BID_AMOUNT] end) PERSISTED,
[SEQUENCE_ID] [int] NULL,
[DELETED] [bit] NOT NULL,
[DELETED_DATE_UTC] [datetime] NULL,
[DELETED_USER_ID] [int] NULL,
CONSTRAINT [PK_OPPORTUNITY] PRIMARY KEY CLUSTERED
(
[INSTANCE_ID] ASC,
[OPPORTUNITY_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
Turns out the current version of Dapper.FastCrud doesn't properly support computed columns. Please watch for a resolution to this ticket.
UPDATE: The problem was fixed in 2.3.0.

how to use c# variables in sql commands

This is what I want to use;
string insertQuery = #"insert into userinfo (UserName, FirstName, LastName,
E-mail, Password, Country)
values ( '" + uname + "', '" + fname +
"','" + lname + "', '" + email + "')";
where every one of the variables in between the + are string variables with values in them. but when I run this command, I get some incorrect syntax error.
This is the new error i get;
errorSystem.Data.SqlClient.SqlException (0x80131904): String or binary
data would be truncated. The statement has been terminated. at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1
completion, String methodName, Boolean sendToPipe, Int32 timeout,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
Registration.RegistrationPage.Button1_Click1(Object sender, EventArgs
e) in c:\Users\kristhnen.jagambrum\Documents\Visual Studio
2012\Projects\Registration\Registration\RegistrationPage.aspx.cs:line
50 ClientConnectionId:6d959e49-5b62-43be-b202-76f7eb1fbd2c
It's very good that you asked - the code that you show is a perfect illustration of two security issues in a single line:
The table structure is an illustration of what lets hackers steal user passwords.
The C# code is what makes SQL injection attacks possible.
Fixing the first problem is hard: you need to learn about password hashing and how to store user info in DB. Here is a Q&A that will help: Best way to store passwords in DB
The second problem is easier - all you need is replacing the injected values with parameter names, and then adding the values for each parameter name:
... // Create SQL command, then set its text
command.CommandTest = #"INSERT INTO userinfo (
UserName, FirstName, LastName, E-mail, Password_hash, Password_salt, Country
) VALUES ( #uname, #fname, #lname, #email, #pwd_hash, #pwd_salt, #country)";
// Bind the parameters
command.Parameters.Add(new SqlParameter("#uname", uname));
command.Parameters.Add(new SqlParameter("#fname", fname));
... // ...and so on
command.ExecuteNonQuery();
The answer is you don't, because it is a bad idea. You should be using SQlCommand instead
Check This out,and there are plenty of examples of how to use it. Appending variables in the way you doing is considered to be the mistake number 3 in the list of 25 most dangerous programming mistakes.
Try something like this, and not use direct parameter in sql command
public const string InsertStmtUsersTable = "insert into userinfo (UserName, FirstName, LastName,
[E-mail], Password, Country) values (#UserName, #FirstName, #LastName,
#[E-mail], #Password, #Country) "
using(SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(InsertStmtUsersTable, conn))
{
command.CommandType = CommandType.Text;
command.Parameters.Add(new SqlParameter("username", userNameString));
command.Parameters.Add(new SqlParameter("FirstName", FirstNameString));
// Rest of your Parameters here
command.ExecuteNonQuery();
}
}

Error in Inserting data in SQL table

I am trying to insert data in a table (say feedback) with columns from(int) and Message(Varchar(MAX)) via c# code but it is continuously annoying me with errors. Please help, I am desperate.
Table description:
From int,Message Varchar(max)
Code I'm using:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleConnectionString"].ConnectionString);
con.open;
string query="insert into Feedback (From,Message) values(#frm,#msg)";
SqlCommand comm = new SqlCommand(query, con);
comm.Parameters.AddWithValue("#frm", Convert.ToInt32(TextBoxid.Text));
comm.Parameters.AddWithValue("#msg",TextBoxFeedBack.text);
comm.ExecuteNonQuery();
con.Close();
The Error I'm getting is
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near
the keyword 'From'. at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj) at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, DbAsyncResult result) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult
result, String methodName, Boolean sendToPipe) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
_Default.Button1_Click(Object sender, EventArgs e) in c:\Users\Ajaz\Documents\Visual Studio
2010\WebSites\WebSite26\Default.aspx.cs:line 29
I'm guessing there's error related to data mismatch. Please help.
Thanks
FROM is a reserved keyword in TSQL. You should use it with square brackets like [FROM]
string query="insert into Feedback ([From],Message) values(#frm,#msg)";
As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Also use using statement to dispose your SqlConnection like;
string query = "insert into Feedback ([From],Message) values(#frm,#msg)";
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleConnectionString"].ConnectionString))
{
SqlCommand comm = new SqlCommand(query, con);
comm.Parameters.AddWithValue("#frm", Convert.ToInt32(TextBoxid.Text));
comm.Parameters.AddWithValue("#msg",TextBoxFeedBack.text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
}
"From" is the reserved word. Surround it by square brackets:
string query="insert into Feedback ([From],Message) values(#frm,#msg)";
Well, the word FROM is a well known keyword in any SQL language existing in the world. If you want to use it (very bad move) then you need to encapsulate it in square brackets
string query="insert into Feedback ([From],Message) values(#frm,#msg)";
Again, don't do that, change the name of the column before having to much code to change.
Otherwise you will have this problem for the lifetime of your app.

NHibernate.Exceptions.GenericADOException why?

I have this
return session.Query<CoursePermission>().Where(x => x.Student.StudentId == studentId).ToList();
I get this
NHibernate.Exceptions.GenericADOException was unhandled by user code
Message=could not execute query
[ select courseperm0_.PermissionId as Permissi1_3_, courseperm0_.Owner as Owner3_, courseperm0_.Add as Add3_, courseperm0_.Edit as Edit3_, courseperm0_.Delete as Delete3_, courseperm0_.View as View3_, courseperm0_.StudentId as StudentId3_, courseperm0_.CourseId as CourseId3_ from CoursePermissions courseperm0_ where courseperm0_.StudentId=#p0 ]
Name:p1 - Value:757f27a2-e997-44f8-b2c2-6c0fd6ee2c2f
[SQL: select courseperm0_.PermissionId as Permissi1_3_, courseperm0_.Owner as Owner3_, courseperm0_.Add as Add3_, courseperm0_.Edit as Edit3_, courseperm0_.Delete as Delete3_, courseperm0_.View as View3_, courseperm0_.StudentId as StudentId3_, courseperm0_.CourseId as CourseId3_ from CoursePermissions courseperm0_ where courseperm0_.StudentId=#p0]
Source=NHibernate
SqlString=select courseperm0_.PermissionId as Permissi1_3_, courseperm0_.Owner as Owner3_, courseperm0_.Add as Add3_, courseperm0_.Edit as Edit3_, courseperm0_.Delete as Delete3_, courseperm0_.View as View3_, courseperm0_.StudentId as StudentId3_, courseperm0_.CourseId as CourseId3_ from CoursePermissions courseperm0_ where courseperm0_.StudentId=#p0
StackTrace:
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
at NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results)
at NHibernate.Impl.SessionImpl.List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results)
at NHibernate.Impl.SessionImpl.List(IQueryExpression queryExpression, QueryParameters parameters)
at NHibernate.Impl.ExpressionQueryImpl.List()
at NHibernate.Linq.NhQueryProvider.ExecuteQuery(NhLinqExpression nhLinqExpression, IQuery query, NhLinqExpression nhQuery)
at NHibernate.Linq.NhQueryProvider.Execute(Expression expression)
at NHibernate.Linq.NhQueryProvider.Execute[TResult](Expression expression)
at Remotion.Data.Linq.QueryableBase`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at PermissionLevelRepo.GetPermission(Guid studentId) line 28
at For(String email) in :line 63
at (String email) in :line 50
at PlannerController.Tab() :line 43
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.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException: System.Data.SqlClient.SqlException
Message=Incorrect syntax near the keyword 'Add'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=15
LineNumber=1
Number=156
Procedure=""
Server=mssql.frostyserver.com
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
InnerException:
Looks like StudentId is a Guid. Try:
return session
.Query<CoursePermission>()
.Where(x => x.Student.StudentId.Equals(studentId))
.ToList();
EDIT: The inner exception:
Message=Incorrect syntax near the keyword 'Add'
The generated sql has a column called Add, try renaming this in your mapping rules.
select courseperm0_.PermissionId as Permissi1_3_, courseperm0_.Owner as Owner3_, courseperm0_.Add as Add3_, ...

Categories

Resources