sql view with hebrew column names errors - c#

i use C# to display sql view in datagridview
i have the following view with hebrew for column names
CREATE VIEW [fixes_view]
AS
SELECT f.fixId AS N'מס תיקון',
f.receiveDate AS N'ת.קבלה',
c.clientName AS N'שם לקוח',
m.modelName AS N'דגם',
f.problem AS N'תיאור תקלה',
f.comments AS N'הערות',
e.employeeName AS N'שם עובד',
f.priceOffer AS N'מחיר ראשונ',
f.price AS N'מחיר סופי',
f.returned AS N'הוחזר'
FROM fixes f
INNER JOIN clients c
ON f.clientId = c.clientId
INNER JOIN modelist m
ON f.modelID = m.modelID
INNER JOIN employees e
ON f.employeeId = e.employeeId
when i want to use it in C# and call it with another condition using
public DataTable GetAllActiveFixTable()
{
return genericGetFixTable("WHERE returned=0;");
}
i tried to refer to the "AS" name 'הוחזר' but it gives me an error when i call it
error:
Invalid column name 'returned'.
private DataTable genericGetFixTable (string str)
{
return genericGetTable("select * FROM [fixes_view] " + str);
}
create table fixes (
fixId int IDENTITY(1,1) primary key,
receiveDate date not null,
clientId int not null,
modelID int not null,
problem nvarchar(100) not null,
comments nvarchar(50),
employeeId int not null,
priceOffer real,
price real,
returned bit,
foreign key (clientId)
references clients,
foreign key (modelID)
references modelist,
foreign key (employeeId)
references employees)

Related

How can I convert SQL to lambda expressions

In my database, I created the tables structure as follows.
CREATE TABLE Course
(
Course_ID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(255) NOT NULL,
);
CREATE TABLE Student
(
Stu_ID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(255) NOT NULL,
Mobile varchar(255),
Age int,
Course_ID int,
FOREIGN KEY (Course_ID) REFERENCES Course(Course_ID)
);
CREATE TABLE Subject
(
Sub_ID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(255) NOT NULL,
);
CREATE TABLE Teacher
(
Teach_ID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(255) NOT NULL,
Mobile varchar(255)
);
CREATE TABLE Course_Subject
(
CouSub_ID int IDENTITY(1,1) PRIMARY KEY,
Course_ID int,
Sub_ID int,
FOREIGN KEY (Course_ID) REFERENCES Course(Course_ID),
FOREIGN KEY (Sub_ID) REFERENCES Subject(Sub_ID)
);
CREATE TABLE Teacher_Subject
(
TeachSub_ID int IDENTITY(1,1) PRIMARY KEY,
Teach_ID int,
Sub_ID int,
FOREIGN KEY (Teach_ID) REFERENCES Teacher(Teach_ID),
FOREIGN KEY (Sub_ID) REFERENCES Subject(Sub_ID)
);
Now my problem is I need to retrieve students data who learned from some teacher, which means need to retrieve some teacher's students who learned from his/her. To accomplish my requirement. I write this SQL query.
select
s.*
from
tbl_student s
inner join
Course_Subject tcs on s.Course_Id = tcs.Course_Id
inner join
Teacher_Subject tst on tst.Sub_ID = tcs.Sub_ID
inner join
Teacher t on t.Teach_ID = tst.Teach_ID
where
t.Teach_ID = #SomeTeacherId
Now I need to convert this query to a lambda expression or Linq. How can I do it? Please help me. Have any possible way to generate this using Visual Studio.
Well, you could use EF to generate object mapping to your tables. And use LINQ to rewrite your query with a slightly different syntax:
var result = from students in tbl_student
join subjects in Course_Subject on students.Course_Id == subjects.Course_Id
join ts in Teacher_Subject on subjects.Sub_ID == ts.Sub_ID
join teachers in Teacher on teachers.Teach_ID == ts.Teach_ID
where teachers.Teach_ID == "your_value"
select students;
Not sure it's an absolutely correct query, but I hope you'll get the main idea.
Have any possible way to generate this using Visual Studio.?
Yes, you can do this using Linq-to-SQL
for your query, this might be appropriated
var students = from student in db.Students
join tcs in db.CourseSubjects on student.CourseId equals tcs.CourseId
join tst in db.TeacherSubjects on tcs.SubId equals tst.SubId
join t in db.Teachers on tst.TeachId equals t.TeachId
where t.TeachId == someTeacherId
select student;
Lambda:
Students
.Where(x=> x.Course.Course_Subjects
.Any(y => y.Subject.Teacher_Subjects
.Any(z => z.Teach_ID == someTeacherId)
)
)
.Select(x => x)

Left outer join runtime error with LINQ

I'm trying to write a left outer join query with Linq on 2 tables, but getting NULL reference exception during runtime, when there are null values in the right table.
For all MatchID values as on tbl_Match table tbl_UserBets table does not have values for all. Hence when NULL value comes up, I'm getting run time exception
PFB my LINQ query,
string userID = "dfa3c0e7-2aa3-42ee-a7d3-803db902dc56";
var res2 = dbEntity.tbl_Match.Select(m => new
{
MatchID = m.MatchID,
Team1 = m.Team1,
Team2 = m.Team2,
UserForTeam1 = dbEntity.tbl_UserBets.Where(b => b.UserForTeam1 == userID).FirstOrDefault(b => b.MatchID == m.MatchID),
UserForTeam2 = dbEntity.tbl_UserBets.Where(b => b.UserForTeam2 == userID).FirstOrDefault(b => b.MatchID == m.MatchID)
});
foreach (var item in res2)
{
Console.WriteLine(item.MatchID + " " + item.Team1 + " vs " + item.Team2 + " " + item.UserForTeam1 == null ? " NA " : item.UserForTeam1.UserForTeam1);
}
SQL Table design for tbl_Match table:
Create Table tbl_Match(
MatchID int primary key Identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
Team1 int Foreign key references tbl_TournamentTeams(TeamID),
Team2 int Foreign key references tbl_TournamentTeams(TeamID),
StartTime DateTime not null,
MatchBetAmount int not null
);
SQL Table design for tbl_UserBets table:
Create Table tbl_UserBets(
UserBetSlNo int primary key identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
MatchID int Foreign key references tbl_Match(MatchID),
UserForTeam1 nvarchar(128) Foreign key references AspNetUsers(Id),
UserForTeam2 nvarchar(128) Foreign key references AspNetUsers(Id),
UserForNoBets nvarchar(128) Foreign key references AspNetUsers(Id)
);
With the below query in SQL i'm able to get the results properly, Need to do the same with LINQ.
select DISTINCT(tbl_Match.MatchID),tbl_Match.Team1,tbl_Match.Team2,tbl_Match.StartTime,tbl_Match.MatchBetAmount,tbl_UserBets.UserForTeam1,tbl_UserBets.UserForTeam2,tbl_UserBets.UserForNoBets from tbl_Match left outer join tbl_UserBets on tbl_Match.MatchID = tbl_UserBets.MatchID and (tbl_UserBets.UserForTeam1 = 'dfa3c0e7-2aa3-42ee-a7d3-803db902dc56' or tbl_UserBets.UserForTeam2 = 'dfa3c0e7-2aa3-42ee-a7d3-803db902dc56')
Please let me know, what changes i should be doing to fix the issue. Thanks.
try merging the where condition with the first or default
i'm guessing the problem is when the where returns null the first or default will cause the exception as stated by msdn doc
var res2 = dbEntity.tbl_Match.Select(m => new
{
MatchID = m.MatchID,
Team1 = m.Team1,
Team2 = m.Team2,
UserForTeam1 = dbEntity.tbl_UserBets.FirstOrDefault(b => b.UserForTeam1 == userID && b.MatchID == m.MatchID),
UserForTeam2 = dbEntity.tbl_UserBets.FirstOrDefault(b => b.UserForTeam2 == userID && b.MatchID == m.MatchID)
});

How to map foreign key for computed column in Entity Framework

I have 2 tables, REGISTRATION and STATUS_CODE
CREATE TABLE [dbo].[REGISTRATION](
[REG_ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL PRIMARY KEY,
[TYPE] [char](1),
[CREDIT_STATUS] [varchar](4) NULL,
[CREDIT_STATUS2] [varchar](4) NULL,
[CREDIT_STATUS_TEMP] AS (case when [TYPE] = '1' then [CREDIT_STATUS] when [TYPE] = '2' then [CREDIT_STATUS2] end)
)
CREATE TABLE [dbo].[STATUS_CODE](
[STATUS_CODE] [varchar](4) NOT NULL PRIMARY KEY,
[STATUS_DESC] [varchar](10),
)
Which my ultimate goal is to run the following query using EF
SELECT REG.REG_ID, STS.STATUS_DESC FROM [dbo].[REGISTRATION] REG
INNER JOIN [dbo].[STATUS_CODE] STS
ON REG.CREDIT_STATUS_TEMP = STS.STATUS_CODE
WHERE STS.STATUS_DESC LIKE '%FAILED%'
In C#, I have the following annotation in REGISTRATION class for the computed column
...
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[ForeignKey("CreditStatusTemp")]
[StringLength(4)]
public string CREDIT_STATUS_TEMP { get; private set; }
public virtual STATUSC_CODE CreditStatusTemp { get; set; }
...
However, whenever I try to save the REGISTRATION record.
I will hit this error.
{"A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'CREDIT_STATUS_TEMP'."}
I know I need the FK annotation to perform the query but I not sure how to do it correctly. Please help, Thanks.

How can I use Dapper with a SELECT stored procedure containing an INNER JOIN between two tables?

I am experimenting with Dapper for the first time. I have two tables: Films and Ratings.
CREATE TABLE [dbo].[Films]
(
[Id] INT NOT NULL PRIMARY KEY,
[Title] VARCHAR(250) NOT NULL,
[Genre] VARCHAR(50) NOT NULL,
[RatingId] INT NOT NULL,
CONSTRAINT [FK_Films_To_Ratings] FOREIGN KEY (RatingId) REFERENCES Ratings(Id)
)
CREATE TABLE [dbo].[Ratings]
(
[Id] INT NOT NULL PRIMARY KEY,
[Name] VARCHAR(50) NOT NULL
)
I have written a stored procedure that will return all films in the Films table and joins with the Ratings table. Dapper works easily when I have the table structured using the same name between the FK and PK of the tables.
CREATE PROCEDURE [dbo].[GetFilms]
AS
BEGIN
SELECT
F.Id,
F.Title,
F.Genre,
F.RatingId,
R.Name
FROM
dbo.Films as F
INNER JOIN
dbo.Ratings as R
ON
F.RatingId = R.Id;
END
When my query runs, the film object becomes instantiated correctly but the RatingId was set to 0 (since int defaults to 0). The rating property contains the name, but the Id was also set to 0.
return this._db.Query<Film, Rating, Film>(
"dbo.GetFilms",
(f, r) =>
{
f.Rating = r;
return f;
},
splitOn: "RatingId",
commandType: CommandType.StoredProcedure
).ToList();
How can I successfully run my Dapper query and get the exact results I need when the column names are not identical like in my example? Table structure looks cleaner to me when I have columns named Ratings.Id instead of Ratings.RatingId.
Dapper will try and map property for property at the point you start splitting. You want your query to look like the following, and you can ditch the splitOn since you are splitting on Id.:
SELECT
F.Id,
F.Title,
F.Genre,
--Rating object starts here
R.Id,
R.Name
FROM
dbo.Films as F
INNER JOIN
dbo.Ratings as R
ON
F.RatingId = R.Id;

SubSonic 2.1: Need explanation of SqlQuery.ExecuteJoinedDataSet()

I have a SqlQuery that looks like this:
SqlQuery query =
DB.Select(
Order.Schema.TableName + ".*",
OrderDetail.Schema.TableName + ".*")
.From<Order>()
.InnerJoin<OrderDetail>()
.Where(Order.IdColumn).IsEqualTo(1);
Now I would expect the Method SqlQuery.ExecuteJoindDataSet() to generate a DataSet for me, that contains 2 DataTables (one for Orders, one for OrderDetails) and put a DataRelation into the DataSet, so I don't have to do this all by hand.
But ExecuteJoinedDataSet() only generates one Table containing all the data from Order but not from OrderDetail:
// Order = 104 Columns
// OrderDetail = 74 Columns
query.ExecuteJoinedDataSet().Tables.Count => 1
query.ExecuteJoinedDataSet().Tables[0].Columns.Count => 104
query.ExecuteDataSet().Tables[0].Columns.Count => 177
I think I am on the right way, but can someone please tell me, what I am doing wrong?
The purpose of this is that the Printing Component I use in my project does not accept generic objects, but DataSet's as a DataSource.
ExecuteJoinedDataSet actually uses all the table columns from the first table and replaces the value in any column that has a foreign key with the first non-forgeign-key value from the corresponding row in the foreign table. It does inner joins for non-null foreign-key columns, and left joins for nullable ones.
So for this schema
create table tblBaseType
(
id int not null primary key identity(1,1),
name not null varchar(100) unique
)
create table tblBaseLocation
(
id int not null primary key identity(1,1),
name not null varchar(100) unique
)
create table tblBase
(
id int not null primary key identity(1,1),
name varchar(100) not null unique,
baseTypeID int not null references tblBaseType(id),
baseLocationID int null references tblBaseLocation(id)
)
and a SqlQuery like
SqlQuery q = new Select().From(TblBase.Schema).Where(TblBase.IdColumn).IsEqualTo(1);
DataSet ds = q.ExecuteJoinedDataSet();
this approximate sql would be generated:
select tblBase.Id,
tblBase.Name,
tblBaseType.Name as baseTypeId,
tblBaseLocation.name as baseLocationId
from tblBase
inner join tblBaseType on tblBase.baseTypeID = tblBaseType.id
left join tblBaseLocation on tblBase.baseLocationID = tblBaseLocation.id
The actual sql is fully qualified, this is just a rough from-scratch approximation.

Categories

Resources