Local sequence cannot be used in LINQ to SQL implementations - asp.net

So here is what i am trying to do. I have tables from the DB and 1 list of member. I get the member from the asp.net membership controls and it a combined membership and profile object. I have a function that will return a list the following Mems object:
Public Property FirstName As String = ""
Public Property LastName As String = ""
Public Property Address1 As String = ""
Public Property Address2 As String = ""
Public Property City As String = ""
Public Property State As System.Int32 = "0"
Public Property Zip As String = ""
Public Property Title As String = ""
Public Property Phone As System.Decimal = "0"
Public Property Id As System.Int32 = "0"
Public Property UserType As System.Int32 = "0"
Public Property SSN As System.Int32 = "0"
Public Property Email As String = ""
Public Property UserName As String = ""
Public Property IsLockedOut As Boolean = False
Private Loaded As Boolean = False
then I have the 2 tables of Jobs and Accounts:
Jobs
JobId numeric(18,0)
AccountId numeric(18,0)
Name varchar(50)
Frequency int
Modifier varchar(90)
Active bit
sDate date
eDate date
Accounts
AccountId numeric(18,0)
CompanyId numeric(18,0)
ContactId varchar(256)
Type int
Name varchar(256)
Address1 varchar(50)
Address2 varchar(50)
City varchar(50)
State int
Zip varchar(5)
AuthCode varchar(10)
Comments text
The output I am trying to achieve is a list of Jobs for the accounts for a particular companyid with the info from the mems. I have it working elsewhere for the accounts, but when i throw the jobs in the mix, It give me the error of:
Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.
Here is where I have gotten with the function as of the moment:
<System.Web.Services.WebMethod(EnableSession:=True)> _
Public Shared Function JobSearch(jSon As String) As String
Dim DamnSer As New JavaScriptSerializer
Dim Search As SearchString = DamnSer.Deserialize(Of SearchString)(jSon)
Dim myDB As New MyDbDataContext
Dim pro As New Mems(HttpContext.Current.User.Identity.Name)
Dim acc = From a In myDB.Accounts Where a.CompanyId = pro.Id Select a
Dim accList = acc.Where(Function(r) r.AccountId).[Select](Function(r) r.AccountId.ToString()).ToArray()
Dim q = From u In Util.GetMems Join a In acc On a.ContactId Equals u.UserName
Where u.FirstName.ToLower.Contains(Search.FirstName.ToLower) And
u.LastName.ToLower.Contains(Search.LastName.ToLower) And
a.Name.ToLower.Contains(Search.Name.ToLower) And
a.ContactId.ToLower.Contains(Search.Email.ToLower) And
u.Phone.ToString.Contains(Search.Phone.ToLower) And
a.AccountId.ToString.Contains(Search.AccountId.ToLower)
Select New With {.FirstName = u.FirstName,
.LastName = u.LastName,
.Name = a.Name,
.Email = u.Email,
.Phone = u.Phone,
.AccountId = a.AccountId,
.City = a.City,
.State = (From s In myDB.States Where s.StateId = a.State Select s.StateAbbr).Single
}
'This is the only line i added between what I have working and this new section and it is where the error happens
Dim qq = From j In myDB.Jobs Where accList.Contains(j.AccountId) Select New With {j.JobId, j.Name, (From z In q Where z.AccountId = j.AccountId).Single}
Return DamnSer.Serialize(qq)
End Function

I decided to go a different route with it
<System.Web.Services.WebMethod(EnableSession:=True)> _
Public Shared Function JobSearch(jSon As String) As String
Dim DamnSer As New JavaScriptSerializer
Dim Search As SearchString = DamnSer.Deserialize(Of SearchString)(jSon)
Dim myDB As New MyDbDataContext
Dim pro As New Mems(HttpContext.Current.User.Identity.Name)
Dim acc = From a In myDB.Accounts Where a.CompanyId = pro.Id Select a
Dim q = From u In Util.GetMems Join a In acc On a.ContactId Equals u.UserName
Where u.FirstName.ToLower.Contains(Search.FirstName.ToLower) And
u.LastName.ToLower.Contains(Search.LastName.ToLower) And
a.Name.ToLower.Contains(Search.Name.ToLower) And
a.ContactId.ToLower.Contains(Search.Email.ToLower) And
u.Phone.ToString.Contains(Search.Phone.ToLower) And
a.AccountId.ToString.Contains(Search.AccountId.ToLower)
Select New With {.FirstName = u.FirstName,
.LastName = u.LastName,
.Name = a.Name,
.Email = u.Email,
.Phone = u.Phone,
.AccountId = a.AccountId,
.City = a.City,
.State = (From s In myDB.States Where s.StateId = a.State Select s.StateAbbr).Single,
.zip = a.Zip,
.Locations = (From l In myDB.Locations Where l.AccountId = a.AccountId Select New With {l.AccountId, l.Address1, l.Address2, l.City, l.Comments, l.LocationId, .State = (From s In myDB.States Where s.StateId = l.State Select s.StateAbbr).Single, l.Zip,
.JobCount = (From j In myDB.Jobs Where j.LocationId = l.LocationId Select j).Count}
)
}
Return DamnSer.Serialize(q)
End Function

Related

it is showing object cannot cast to DBNull

SqlCommand sd1 = new SqlCommand("select sum(pric) from cart where uid='" +
Convert.ToInt32( Session["uid"]) + "'",con);
// sd1.ExecuteNonQuery();
int var1 = Convert.ToInt32( sd1.ExecuteScalar());
If there is no record then DBNull.Value is returned instead. You need to account for this in your casting. The following will cast to a nullable int so you have a representation if no records were found.
Also use parameters for your queries, not string concatenation.
Code:
int? intResult;
using(SqlCommand sd1 = new SqlCommand("select sum(pric) from cart where uid=#uid", con))
{
sd1.Parameters.Add(new SqlParameter("#uid", SqlDbType.Int){Value = Convert.ToInt32(Session["uid"])});
var result = sd1.ExecuteScalar();
intResult = Syste.DBNull.Value == result
? (int?) null
: (int?) result;
}

is there a way to get rid of DTO

I am using Entity Framework. I have the following query in which I get data using two tables Application and Employee connected by a foreign key EmployeeID in Application Table. The tables have 1-1 relationship .
Is there a way to simplify the following code and get rid of the DTO Employee1
which is the same as auto generated Employee class
public List<Employee1> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = (from a in context.Applications
join e in context.Employees on a.EmployeeID equals e.EmployeeID
where
(
a.ApplicationID == ApplicationID
)
select new Employee1
{
EmployeeID = e.EmployeeID,
SecondEmail = e.SecondEmail,
EmailID = e.EmailID,
Title = e.Title,
Name = e.Name,
Rank = e.Rank,
POBox = e.POBox,
Phone = e.Phone,
JoinDate = e.JoinDate,
Status = e.Status,
DepartmentID = e.DepartmentID.Value,
NameString = e.NameString,
Department = e.Department,
ParentDept = e.ParentDept,
DepartmentAr = e.DepartmentAr,
NameAr = e.NameAr,
NameStringAr = e.NameStringAr,
TitleAr = e.TitleAr
}).ToList();
return data;
}
If you need to return list of Employees, just select e which refers to Employee and don't use Employee1 as a DTO.
public List<Employee> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = (from a in context.Applications
join e in context.Employees on a.EmployeeID equals e.EmployeeID
where
(
a.ApplicationID == ApplicationID
)
select e).ToList();
return data;
}
Another way is this, which I would prefer because of readability:
public List<Employee> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = context.Applications.Where(p=>p.ApplicationID == ApplicationID).Select(p=>p.Employee).ToList();
return data;
}

Linq members with profiles

I am trying to make a linq query to pull all users in the membership with their profiles. Here is what I have gotten already:
Dim Mbrs = Membership.GetAllUsers
Dim Pros = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All)
Dim q = From mem In Mbrs Join pro In Pros On mem.UserName Equals
pro.UserName Select mem.email, mem.username, mem.islockedout,
pro.FirstName, pro.lastname, pro.city, pro.state, pro.zip, pro.type
If i take the profile stuff off the select, it will at least pull a list of members. What am I doind wrong??
Make a Class like this
Imports Microsoft.VisualBasic
Public Class Mems
Public Property FirstName As String = ""
Public Property LastName As String = ""
Public Property Address1 As String = ""
Public Property Address2 As String = ""
Public Property City As String = ""
Public Property State As System.Int32 = "0"
Public Property Zip As String = ""
Public Property Title As String = ""
Public Property Phone As System.Decimal = "0"
Public Property Id As System.Int32 = "0"
Public Property UserType As System.Int32 = "0"
Public Property SSN As System.Int32 = "0"
Public Property Email As String = ""
Public Property UserName As String = ""
Public Property IsLockedOut As Boolean = False
Private Loaded As Boolean = False
Public Sub New(usr As String)
GetMem(usr)
End Sub
Public Sub New()
End Sub
Public Sub Save()
If Not Loaded Then Throw New Exception("No User Loaded")
Dim mm = Membership.GetUser(UserName)
mm.Email = Email
Membership.UpdateUser(mm)
Dim p As ProfileCommon = New ProfileCommon
Dim pp = p.GetProfile(UserName)
pp.Address1 = Address1
pp.Address2 = Address2
pp.City = City
pp.FirstName = FirstName
pp.Id = Id
pp.LastName = LastName
pp.Phone = Phone
pp.SSN = SSN
pp.State = State
pp.Title = Title
pp.UserType = UserType
pp.Zip = Zip
pp.Save()
End Sub
Public Sub GetMem(usr As String)
'Try
If usr.Length = 0 Then
FirstName = "SYSTEM"
Else
Dim mm = Membership.GetUser(usr)
Email = mm.Email
IsLockedOut = mm.IsLockedOut
Dim p As ProfileCommon = New ProfileCommon
Dim pp = p.GetProfile(usr)
Address1 = pp.Address1
Address2 = pp.Address2
City = pp.City
FirstName = pp.FirstName
Id = pp.Id
LastName = pp.LastName
Phone = pp.Phone
SSN = pp.SSN
State = pp.State
Title = pp.Title
UserType = pp.UserType
Zip = pp.Zip
UserName = usr
Loaded = True
'Catch ex As Exception
' End Try
End If
End Sub
Public Function ChangeUsername(uTo As String) As Integer
If Loaded Then
Return ChangeUsername(UserName, uTo)
Else
Throw New Exception("No User Loaded")
End If
End Function
Public Function ChangeUsername(uFrom As String, uTo As String) As Integer
If Membership.FindUsersByName(uFrom).Count = 0 Then
Throw New Exception("Original UserName Don't Exists")
ElseIf Membership.FindUsersByName(uTo).Count = 1 Then
Throw New Exception("Target UserName Don't Exists")
Else
Dim myDb As New MyDbDataContext
Dim q = (From u In myDb.aspnet_Users Where u.UserName = uFrom And u.ApplicationId.Equals("72e4b882-e471-4f4b-b161-af0abbcb8487") Select u).Single
q.UserName = uTo
q.LoweredUserName = uTo.ToLower
Try
myDb.SubmitChanges()
Return 1
Catch ex As Exception
Return 0
End Try
End If
End Function
End Class
then you can call it from a functions like this
Public Shared Function GetMems() As List(Of Mems)
GetMems = New List(Of Mems)
Dim mm = Membership.GetAllUsers
For Each mbr As MembershipUser In mm
GetMems.Add(New Mems(mbr.UserName))
Next
Return GetMems
End Function

How can I store sql table row count in a string variable?

I am trying to store the result of query string
q = "select count(*) from test" (asp.net c#)
in a string variable so that I can display the count on a label on button click.
int RecordCount;
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
string myString = RecordCount.ToString();
The value of ExecuteScalar can be null, make sure you check for null
int RecordCount = 0;
object retVal = cmd.ExecuteScalar();
if(retVal != null)
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());

Conversion from string "" to type 'Double' is not valid

I have a variable that contains an integer which I then want to save as the value for a column (of type integer in the sql database and int32 in the entity model), but when I try this I receive the error:
"Conversion from string "" to type 'Double' is not valid"
I'm very confused by this since I'm not using a string or a double? The trouble-making line is:
UpdateBed.First.occupant = GetID
And here is the full code snippet:
Private Sub btnReserve_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReserve.Click
Using dbContext As pbu_housingEntities = New pbu_housingEntities
' Check that the room is still available.
Dim hall As String = CStr(Session("hall"))
Dim room As String = CStr(Session("room"))
Dim checkOccupants = From p In dbContext.Rooms _
Let building_id = p.Building1.id _
Where p.building_name = hall _
Where p.room1 = room _
Select p.current_occupancy, p.max_occupancy, p.id, building_id
If checkOccupants.First.current_occupancy >= checkOccupants.First.max_occupancy Then
' If it isn't available, let the student know.
lblResult.Text = "Sorry, this room is now fully occupied. Please choose another room."
Else
' If it is available, add the student to the room.
Dim Occupant As New Resident
Dim gender As String = CStr(Session("gender"))
Dim person_name As String = CStr(Session("person_name"))
Dim class_level As String = CStr(Session("class_level"))
Dim semester As String = CStr(Session("term"))
Dim people_code_id As String = CStr(Session("people_code_id"))
Dim first_name As String = CStr(Session("first_name"))
Dim last_name As String = CStr(Session("last_name"))
Dim building_id As String = checkOccupants.First.building_id
Dim room_id As String = checkOccupants.First.id
Occupant.building = building_id
Occupant.room = room_id
Occupant.gender = gender
Occupant.person_name = person_name
Occupant.class_level = class_level
Occupant.semester = semester
Occupant.people_code_id = people_code_id
Occupant.create_date = Date.Now
Occupant.first_name = first_name
Occupant.last_name = last_name
dbContext.Residents.AddObject(Occupant)
' Increment the number of occupants in the room.
Dim UpdateOccupancy = (From p In dbContext.Rooms _
Where p.building_name = hall _
Where p.room1 = room _
Select p).First
UpdateOccupancy.current_occupancy = UpdateOccupancy.current_occupancy + 1
' Add the student to a bed.
Dim UpdateBed = From p In dbContext.Beds _
Where p.building = building_id _
Where p.room = room_id _
Where p.occupant = "" _
Select p
' Get the student's ID from the residency table.
Dim GetID = (From p In dbContext.Residents _
Where p.people_code_id = people_code_id _
Order By p.id Descending _
Select p.id).FirstOrDefault
UpdateBed.First.occupant = GetID
dbContext.SaveChanges()
lblResult.Text = "Success! You have successfully requested residency in this room!"
End If
End Using
End Sub
This line in your LINQ query ...
Where p.occupant = ""
... and this assignment ...
UpdateBed.First.occupant = GetID
don't seem to fit well together (if GetID is an Int32). Shouldn't it be perhaps Where p.occupant = 0 or something?

Resources