Entity Framework not calculating count() after grouping - sql-server

The code will better explain what I'm trying to do.
var data = db.Absences//.AsExpandable()
.Where(a => a.Employee.EmployeeCode == "Emp1" || a.Employee.EmployeeCode == "Emp2" || a.Employee.EmployeeCode == "Emp3" || a.Employee.EmployeeCode == "Emp4" )
.Where(a=> a.Employee.Department.DepartmentCode == "HR" ||a.Employee.Department.DepartmentCode == "FIN" ||a.Employee.Department.DepartmentCode == "IT" )
.Where(a=> a.AbsenceId > 0)
.GroupBy(a => new
{
a.Employee.Department.DepartmentName,
a.Employee.Department.DepartmentCode,
a.Employee.IsPermanent
})
.Select(g => new ResultModel
{
Department = g.Key.DepartmentName,
Permanent = g.Key.IsPermanent,
TotalEmployeesInDepartment = g.Select(e => e.EmployeeCode).Distinct().Count(),
TotalAbsenceRecordsInCategory = g.Count(),
TotalLateCount = g.Select(x=> x.AbsenceCode == "Late").Count(),
TotalSickCount = g.Select(x=> x.AbsenceCode == "Sick").Count(),
TotalOnSiteCount = g.Select(x => x.AbsenceCode == "OnSite").Count(),
LatePercent = g.Select(x => x.AbsenceCode == "Late").Count() * 100.0 / g.Count(),
SickPercent = g.Select(x => x.AbsenceCode == "Sick").Count() * 100.0 / g.Count(),
OnSitePercent = g.Select(x => x.AbsenceCode == "OnSite").Count() * 100.0 / g.Count(),
});
I want total number of absences in a department, grouped by permanent vs non-permanent employees.
TotalAbsenceRecordsInCategory = g.Count() this is calculating fine in the generated SQL.
When I'm trying to get count of absences due to individual reasons the query is not working as expected.
TotalLateCount = g.Select(x=> x.AbsenceCode == "Late").Count(), this is not working, all of them are evaluated as
COUNT(1) AS [A1],
COUNT(1) AS [A2],
COUNT(1) AS [A3],
COUNT(1) AS [A4],.. so on
Below are my tables
CREATE TABLE [dbo].[Employees]
(
[DepartmentCode] [nvarchar](10) NOT NULL,
[EmployeeCode] [nvarchar](10) NOT NULL,
[EmployeeName] [nvarchar](20) NOT NULL,
[IsPermanent] [bit] NOT NULL,
CONSTRAINT [PK_Employees]
PRIMARY KEY CLUSTERED ([DepartmentCode] ASC, [EmployeeCode] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Employees]
ADD CONSTRAINT [DF_Employees_IsPermanent] DEFAULT ((0)) FOR [IsPermanent]
GO
ALTER TABLE [dbo].[Employees] WITH CHECK
ADD CONSTRAINT [FK_Employees_Departments]
FOREIGN KEY([DepartmentCode]) REFERENCES [dbo].[Departments] ([DepartmentCode])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
CREATE TABLE [dbo].[Departments]
(
[DepartmentCode] [nvarchar](10) NOT NULL,
[DepartmentName] [nvarchar](20) NOT NULL,
CONSTRAINT [PK_Departments]
PRIMARY KEY CLUSTERED ([DepartmentCode] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Absences]
(
[DepartmentCode] [nvarchar](10) NOT NULL,
[EmployeeCode] [nvarchar](10) NOT NULL,
[AbsenceId] [int] NOT NULL,
[AbsenceCode] [nvarchar](10) NOT NULL,
[AbsenceDate] [date] NOT NULL,
CONSTRAINT [PK_Absences_1]
PRIMARY KEY CLUSTERED ([DepartmentCode] ASC, [EmployeeCode] ASC, [AbsenceId] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Absences] WITH CHECK
ADD CONSTRAINT [FK_Absences_Employees]
FOREIGN KEY([DepartmentCode], [EmployeeCode]) REFERENCES [dbo].[Employees] ([DepartmentCode], [EmployeeCode])
GO
ALTER TABLE [dbo].[Absences] CHECK CONSTRAINT [FK_Absences_Employees]
GO
One alternative is to say
TotalLateCount = g.Count(x=> x.AbsenceCode == "Late")
but this creates nested sub queries which I'm trying to avoid.
Any idea how can I get this to work? ResultModel is a simple class
public class ResultModel
{
public string Department { get; set; }
public bool Permanent { get; set; }
public int TotalAbsenceRecordsInCategory { get; set; }
public int TotalEmployeesInDepartment { get; set; }
public int TotalLateCount { get; set; }
public int TotalSickCount { get; set; }
public int TotalOnSiteCount { get; set; }
public double LatePercent { get; set; }
public double SickPercent { get; set; }
public double OnSitePercent { get; set; }
}

Related

Sync Framework not Provisiong Sql Compact when number of primary keys are different

I am trying to sync Sql Compact With Sql Server. Every thing works fine if number of primary keys are similar in client and server table. But If number of primary keys are not same in both tables I Get the following Exception
The given key was not present in the dictionary.
Stack Trace:
at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary2.get_Item(TKey key)
at Microsoft.Synchronization.Data.SqlServerCe.SqlCeSyncUtil.GetPkInOrdinalOrder(IEnumerable1 pkColumns, Dictionary`2 pkIndexOrder)
at Microsoft.Synchronization.Data.SqlServerCe.SqlCeSyncTableProvisioning.Apply(SqlCeTransaction trans)
at Microsoft.Synchronization.Data.SqlServerCe.SqlCeSyncScopeProvisioning.ApplyInternal(SqlCeConnection connection)
at Microsoft.Synchronization.Data.SqlServerCe.SqlCeSyncScopeProvisioning.Apply()
at SQLCompactDeployment.Program.ProvisionClient(String ServerConnectionString, String ClientConnectionString, Boolean IsSqlServerCompact) in M:\Windows 2020\Documents\repos\SQLCompactDeployment\SQLCompactDeployment\Program.cs:line 296
Table Structure in Server
USE [Server]
GO
/****** Object: Table [dbo].[Customer] Script Date: 3/26/2020 6:09:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Customer](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](150) NULL,
[TenantId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Customer_1] PRIMARY KEY CLUSTERED
(
[Id] ASC,
[TenantId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
Table Structure In Client
USE [Client]
GO
/****** Object: Table [dbo].[Customer] Script Date: 3/26/2020 6:09:20 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Customer](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](150) NULL,
[TenantId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Customer_1] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
Syncing Code
public static bool ProvisionServer(string ServerConnectionString)
{
try
{
string scopeName = "SyncScope";
SqlConnection serverConn = new SqlConnection(ServerConnectionString);
DbSyncScopeDescription SyncScope = new DbSyncScopeDescription(scopeName);
DbSyncTableDescription Customer = SqlSyncDescriptionBuilder.GetDescriptionForTable("Customer", serverConn);
SyncScope.Tables.Add(Customer);
SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, SyncScope);
serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip);
serverProvision.Apply();
return true;
}
catch (Exception ex)
{
return false;
}
}
public static bool ProvisionClient(string ServerConnectionString, string ClientConnectionString, bool IsSqlServerCompact)
{
try
{
string scopeName = "SyncScope";
SqlConnection serverConn = new SqlConnection(ServerConnectionString);
DbSyncScopeDescription scopeDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope(scopeName, serverConn);
if (IsSqlServerCompact)
{
SqlCeConnection clientConnCe = new SqlCeConnection(ClientConnectionString);
SqlCeSyncScopeProvisioning clientProvision = new SqlCeSyncScopeProvisioning(clientConnCe, scopeDesc);
clientProvision.Apply();
}
else
{
SqlConnection clientConn = clientConn = new SqlConnection(ClientConnectionString);
SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, scopeDesc);
clientProvision.Apply();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
With the same structure If I sync From Sql server database to Sql server database it Works.

Error converting data type varchar to int using stored procedure

I have two tables, one for primary key and second for foreign key. When I write the code to insert the data, I get an error.
ALTER PROCEDURE [dbo].[ImageHotSpotCRUD]
#ImaheHSMId int = NULL,
#ImaheHSName varchar(MAX) = '' ,
-- #patImage [varbinary](max)= NULL
#ImaheHSPath varchar(MAX) = '' ,
#ImaheHSDId int = NULL,
#ImaheHSDFKId int = NULL,
#ImaheHSXCordinate varchar(50) = '',
#ImaheHSYCordinate varchar(50) = '' ,
#ImaheHSDisc varchar(MAX) = '' ,
#IsActive varchar(1) = '' ,
#Created_by varchar(20) = '' ,
#CreatedDate datetime ='',
#ModifyDate datetime ='',
#ModifyBy varchar(50) = '',
#Mode varchar(1) =''
AS
BEGIN
SET NOCOUNT ON;
IF #Mode = '1'
BEGIN
-- Primary key table entry
DECLARE #ImageNEWPKId int = NULL
SELECT #ImageNEWPKId = HotSpotID
FROM M_ImageHotSpot
WHERE ImageName = #ImaheHSName
IF (#ImageNEWPKId IS NULL)
BEGIN
INSERT INTO M_ImageHotSpot (ImageName, ImagePath, Created_by, Created_date)
VALUES (#ImaheHSName, #ImaheHSPath, #Created_by, GETDATE())
SELECT #ImageNEWPKId = SCOPE_IDENTITY()
END
-- Foreign key table entry
DECLARE #ImageNEWDetailPKId int = NULL
SELECT #ImageNEWDetailPKId = HPDetailID
FROM M_ImageHotSpotDetail
WHERE HotSpotDescription = #ImaheHSDisc
IF (#ImageNEWDetailPKId IS NULL)
BEGIN
INSERT INTO M_ImageHotSpotDetail (HotspotIDFK, XCordinate, YCordinate, HotSpotDescription, CreatedByID, CreatedDate)
VALUES (#ImageNEWPKId, #ImaheHSXCordinate, #ImaheHSYCordinate, #ImaheHSDisc, #Created_by, GETDATE())
-- SELECT #ImaheHSMId = SCOPE_IDENTITY()
END
END
END
Here how I pass the data during button click in aspx.cs page:
exec ImageHotSpotCRUD
#Mode = '1', #ImaheHSName = 'x.jpeg', #ImaheHSPath = 'c:\',
#Created_by = 'ADMIN', #ImaheHSXCordinate = '100', #ImaheHSYCordinate = '100',
#ImaheHSDisc = 'You Selected Computer'
GO
I am using SQL Server Management Studio 18.
EDIT CODE 1
public int ImaheHSMId { get; set; }
public string ImaheHSName { get; set; }
public string ImaheHSPath { get; set; }
//Foreign Key Field
public int ImaheHSDId { get; set; }
//Foreign Key Id store here
public int ImaheHSDFKId { get; set; }
public string ImaheHSXCordinate { get; set; }
public string ImaheHSYCordinate { get; set; }
public string ImaheHSDisc { get; set; }
public string UserId { get; set; }
public bool IsDeleted { get; set; }
public bool IsActive { get; set; }
This are my class property and here is my Table Information. I did every thing perfect but still no data inserted.
Edit Code 2
Here is My both the table script.
CREATE TABLE [TRIEU].[M_ImageHotSpot](
[HotSpotID] [int] IDENTITY(1,1) NOT NULL,
[ImageName] [nvarchar](max) NULL,
[ImagePath] [nvarchar](max) NULL,
[IsActive] [bit] NULL,
[IsDeleted] [bit] NULL,
[Created_by] [nvarchar](18) NULL,
[Created_date] [datetime] NULL,
[Modified_by] [nvarchar](18) NULL,
[Modified_date] [datetime] NULL,
[stats_flag] [char](1) NULL,
CONSTRAINT [PK_M_ImageHotSpot] PRIMARY KEY CLUSTERED
(
[HotSpotID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [TRIEU].[M_ImageHotSpotDetail](
[HPDetailID] [int] IDENTITY(1,1) NOT NULL,
[HotspotIDFK] [int] NULL,
[XCordinate] [nvarchar](50) NULL,
[YCordinate] [nvarchar](50) NULL,
[HotSpotDescription] [nvarchar](max) NULL,
[IsActive] [bit] NULL,
[IsDeleted] [bit] NULL,
[Created_by] [nvarchar](18) NULL,
[Created_date] [datetime] NULL,
[Modified_by] [nvarchar](18) NULL,
[Modified_date] [datetime] NULL,
[stats_flag] [char](1) NULL,
CONSTRAINT [PK_M_ImageHotSpotDetail] PRIMARY KEY CLUSTERED
(
[HPDetailID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Dear JParmar,
INSERT INTO M_ImageHotSpotDetail (HotspotIDFK, XCordinate, YCordinate, HotSpotDescription, CreatedByID, CreatedDate)
VALUES (#ImageNEWPKId, #ImaheHSXCordinate, #ImaheHSYCordinate, #ImaheHSDisc, #Created_by, GETDATE())
For the above line, CreatedByID and CreatedDate column is not exist in M_ImageHotSpotDetail Table.

General Trigger that updates a Master/Detail table

I've been tasked with creating a generic Trigger(one that will work on all tabled in my database) that will will fire on Insert, Delete, and Update to capture changes done on a table.
I have 2 new tables a Master Table...
CREATE TABLE [dbo].[DATA_HIL_Master](
[MasterId] [int] IDENTITY(1,1) NOT NULL,
[ReferenceTable] [nvarchar](100) NULL,
[ReferenceId] [int] NULL,
[OperationType] [smallint] NULL,
[Last_UserId_Log] [int] NULL,
[Last_WorkstationId_Log] [int] NULL,
[Last_DateTime_Log] [datetime] NULL, PRIMARY KEY CLUSTERED (
[MasterId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS
= ON) ON [PRIMARY]
) ON [PRIMARY] GO
And then a Detail table...
CREATE TABLE [dbo].[DATA_HIL_Detail](
[DetailId] [int] IDENTITY(1,1) NOT NULL,
[MasterId] [int] NOT NULL,
[ColumnName] [nvarchar](100) NULL,
[OriginalValue] [nvarchar](max) NULL,
[ModifiedValue] [nvarchar](max) NULL,
PRIMARY KEY CLUSTERED (
[DetailId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO
My trigger needs to be able to update these tables with the correct information for that update and than table. For Instance I have another table..
CREATE TABLE [dbo].[CNF_Tax2Package](
[Tax2PackageId] [int] IDENTITY(1,1) NOT NULL,
[TaxPackageId] [int] NOT NULL,
[TaxId] [int] NOT NULL,
[Last_UserId_Log] [int] NULL,
[Last_WorkstationId_Log] [int] NULL,
[Last_DateTime_Log] [datetime] NULL,
PRIMARY KEY CLUSTERED
(
[Tax2PackageId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY =
OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED
(
[Tax2PackageId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY =
OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
EveryTime a record is change in this CNF_Tax2Package table I need to up the History tables with information
I do the following UPdate statement
Update CNF_Tax2Package
set TaxPackageid = 1,
Last_UserID_Log = 1098,
Last_WorkstationID_Log = 77,
Last_DateTime_Log = Getdate()
where Tax2PackageID = 2]
I would insert into the DATA_HIL_Master a row with the following information
[MasterId] = (NEWMasterID) [ReferenceTable] = 'CNF_Tax2Package' [ReferenceId] = 2 ---This is the primary Key of the
---table updated. [OperationType] = 'Update' [Last_UserId_Log] = 1098 [Last_WorkstationId_Log] = 77 [Last_DateTime_Log] getdate()
I would then insert into the DATA_HIL_Detail the following rows.
[DetailId] = (NEWID) [MasterId] = (NEWMasterID) (From above) [ColumnName] = 'TaxPackageid' [OriginalValue] = '19' [ModifiedValue] = '1'
[DetailId] = (NEWID) [MasterId] = (NEWMasterID) (From above) [ColumnName] = 'Last_UserID_Log' [OriginalValue] = '1954' [ModifiedValue] = '1098'
[DetailId] = (NEWID) [MasterId] = (NEWMasterID) (From above) [ColumnName] = 'Last_WorkstationId_Log' [OriginalValue] = '55' [ModifiedValue] = '77'
[DetailId] = (NEWID) [MasterId] = (NEWMasterID) (From above) [ColumnName] = 'Last_DateTime_Log' [OriginalValue] = '2018-08-18 [ModifiedValue] = getdate()
Understanding that the trigger must be generic enough to handle all tables in my database with different columns, different primary Keys

Dapper > I cannot retrieve object with child object

I have the following Quote and Share classes:
public class Quote
{
public Quote(string ticker, string name, decimal lastPrice)
{
this.Ticker = ticker;
this.Name = name;
this.LastPrice = lastPrice;
}
public string Ticker { get; private set; }
public string Name { get; private set; }
public decimal LastPrice { get; private set; }
}
public class Share
{
public Share(Quote quote, int quantity)
{
this.Quote = quote;
this.Quantity = quantity;
}
public Quote Quote { get; private set; }
public int Quantity { get; private set; }
}
And these tables:
CREATE TABLE [dbo].[quotes](
[ticker] [char](5) NOT NULL,
[name] [varchar](60) NOT NULL,
[last_price] [money] NOT NULL,
[bid_price] [money] NULL,
[bid_quantity] [int] NULL,
[ask_price] [money] NULL,
[ask_quantity] [int] NULL,
[high] [money] NULL,
[low] [money] NULL,
[previous_close] [money] NULL,
[created_by] [varchar](12) NULL,
[created_date] [datetime] NULL,
[modified_by] [varchar](12) NULL,
[modified_date] [datetime] NULL,
CONSTRAINT [PK_quotes] PRIMARY KEY CLUSTERED
(
[ticker] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[shares](
[ticker] [char](5) NOT NULL,
[broker_id] [char](12) NOT NULL,
[quantity] [int] NOT NULL,
[created_by] [varchar](12) NOT NULL,
[created_date] [datetime] NOT NULL,
[modified_by] [varchar](12) NULL,
[modified_date] [datetime] NULL,
CONSTRAINT [PK_shares] PRIMARY KEY CLUSTERED
(
[ticker] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[shares] WITH CHECK ADD CONSTRAINT [FK_shares_quotes] FOREIGN KEY([ticker])
REFERENCES [dbo].[quotes] ([ticker])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[shares] CHECK CONSTRAINT [FK_shares_quotes]
GO
And finally this code:
string sql = "SELECT quantity, s.ticker, name, last_price FROM shares s " +
"INNER JOIN quotes q ON q.ticker = s.ticker " +
"WHERE s.ticker=#ticker AND broker_id = #broker_Id";
IEnumerable<Share> shares = connection.Query<Share, Quote, Share>(sql,
(s, q) =>
{
Share share = new Share(q, s.Quantity);
return share;
},
new { ticker = ticker, broker_Id = brokerId }
, splitOn: "ticker");
return shares.FirstOrDefault();
When I execute that query, I get the following error:
"Specified method is not supported" (???)
If I modify the sql statement by the following (with "last_price as lastPrice"):
string sql = "SELECT quantity, s.ticker, name, last_price as lastPrice FROM shares s " +
"INNER JOIN quotes q ON q.ticker = s.ticker " +
"WHERE s.ticker=#ticker AND broker_id = #broker_Id";
I get the following error:
"A parameterless default constructor or one matching signature (System.String ticker, System.String name, System.Decimal lastPrice) is required for Footstock.Domain.Model.Quote materialization"
What am I doing wrong?
For the Share class, you need to either add a parameterless constructor or one that takes only a quantity parameter.
Before Dapper calls the method that composes the result to be returned, it needs to build the parameters to pass in to (s, q) => ... In your case you need a Share and a Quote class, both of which must have a constructor that can be called using the data Dapper has. For Quote, the constructor matches the properties in the query. For Share, Dapper only has the quantity and does not have a Quote object yet.

foreign key with 'no foreign key' value

In my application I use MS SQL Server 2008 and Linq-to-SQL. I have two tables: A and B, linked with foreign key: B.AId => A.Id. Is it possible in B.AId to have a value, for instance -1, which means 'no A' and ignores foreign key?
I can't use NULL in B.AId because Linq-to-SQL does not correclty support one-to-oneorzero associations (unfortunately).
Created a sample model with tables A and B
CREATE TABLE [dbo].[A](
[Id] [int] NOT NULL,
[AA] [varchar](50) NOT NULL,
[AAA] [varchar](50) NOT NULL,
CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[B](
[Id] [int] NOT NULL,
[BB] [varchar](50) NOT NULL,
[BBB] [varchar](50) NOT NULL,
[AId] [int] NULL,
CONSTRAINT [PK_B] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[B] WITH CHECK ADD CONSTRAINT [FK_B_A] FOREIGN KEY([AId])
REFERENCES [dbo].[A] ([Id])
GO
ALTER TABLE [dbo].[B] CHECK CONSTRAINT [FK_B_A]
GO
After that generated a model from database. Even though it is recognized as a 1 to many relationship a navigation property A is created for table B.
I created a test and created three different rows in table B
Using navigation property A
Using Id of A
Created a row without reference to A
using (var db = new DataClasses1DataContext())
{
// Add sample A row
var sampleARow = new A()
{
Id = 1,
AA = "AA",
AAA = "AAA",
};
db.As.InsertOnSubmit(sampleARow);
db.SubmitChanges();
// Refer to sample A row using navigation property
var sampleNewBRowWithNav = new B()
{
Id = 1,
BB = "BB1",
BBB = "BBB1",
A = db.As.First(),
};
// Refer to sample A row using Id
var sampleNewBRowWithId = new B()
{
Id = 2,
BB = "BB2",
BBB = "BBB2",
AId = 1,
};
// No reference to A
var sampleNewBRowWithoutA = new B()
{
Id = 3,
BB = "BB3",
BBB = "BBB3",
AId = null // strictly not needed, because AId is default null
};
db.Bs.InsertOnSubmit(sampleNewBRowWithNav);
db.Bs.InsertOnSubmit(sampleNewBRowWithId);
db.Bs.InsertOnSubmit(sampleNewBRowWithoutA);
db.SubmitChanges();
}

Resources