Entity framework sqlquery - c#

I read about querying database using the entity framework
var result = _dbContext.SqlQuery<string>(sql, someParamSqlParameter).ToList();
What if i wanted multiple columns to be returned how could i write that type of query.
I tried this code but it gives some sql schema mapping error
var result = clsGlobalObjectRefrances.SchoolSoulController.Stt.Database.SqlQuery<LocalAccGroups>(sqlQuery).ToList();
var sqlQuery = "Select GroupId,GroupName,Level from cte_AccGroups";
Where LocalAccGroups is a class i created
class LocalAccGroups
{
public decimal GroupId { get; set; }
public string GroupName { get; set; }
int Level { get; set; }
}
Thanxxx in Advance

Your query is returning Level as well, and you haven't marked your property Level in your class as public. Mark your property as public and it should be good. Also make sure that the data type matches the one returned by query. It seems odd go a GroupId to be of type decimal.
class LocalAccGroups
{
public decimal GroupId { get; set; }
public string GroupName { get; set; }
public int Level { get; set; }
}

Related

Linq Method Syntax Querying to include Navigational Property information EF Core 3

I am trying to query and have the navigational property (the list) return with the correct number of items in it. Currently what I am doing, the list is always empty (Case_Users property in Case object for the example below) when it should not be.
I have these classes:
public class Case
{
public Case()
{
Create_Date = DateTime.Now;
}
[Key]
public int Id { get; set; }
[MaxLength(1000)]
public string CaseNumber { get; set; }
public ICollection<Case_Users> Case_Users { get; set; } = new List<Case_Users>();
}
public class Case_Users
{
public Case_Users()
{
Create_Date = DateTime.Now;
}
[Key]
public int Id { get; set; }
[ForeignKey("Case")]
public int CaseID { get; set; }
public Case Case { get; set; }
public string Role {get; set;}
}
I want to make it so that I can query using the method syntax, starting with the Case and using its navigational property to get the data from its Case_Users navigational property entries, like this:
var query = _context.Case.Include(c => c.Case_Users).ToList();
I am getting simply my list object returned, but the Case_Users list object is empty. Even though it should not be.
Is it possible to query based on the navigational property, and if so what is the syntax?

The specified type member 'Notes' is not supported in LINQ to Entities

I have a class Student (pseudo code below):
public class Student {
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
}
And a partial class (pseudo code below):
public partial class Student {
public string Notes { get; set; }
public string Instructions { get; set; }
}
Enrollment class:
public class Enrollment {
public int EnrollmentId { get; set; }
public string CourseName { get; set; }
}
LINQ:
var student = dataContext.Student;
var studentEnrollments = student.Join(
dataContext.Enrollment,
s => s.EnrollmentId,
e => e.EnrollmentId,
(s, e) => new
{
id = s.StudentId,
name = s.FirstName,
course = e.CourseName
});
Now when I write a link statement, and I want to order by Notes, or Instructions, I get the error:
The specified type member 'Notes' is not supported in LINQ to Entities.
Now Notes and Instructions are not columns in the Student table in the database. Is that what is throwing this exception? How can I sort based on these two fields, Notes and Exceptions if I need to?
Presumably it's trying to convert your LINQ code into SQL. It can't do so for those two fields because they're not database fields, hence the error.
Try doing the rest of your query, then calling ToList() on it (forcing the SQL part to execute), and then calling OrderBy on the non-database field you want to sort by.

Entity Framework 6 and navigational property issue

Im hoping to get your help here. Im very new to EF and am having some troubles. I am using the Database First approach and have a database in Azure that I have to retreive data from.
[DataContract]
[Table("A")]
public class AgencyDC
{
[DataMember]
[Key]
public string AID { get; set; }
public string AName { get; set; }
public string GeneralEmailAddress { get; set; }
public string WebsiteURL { get; set; }
[DataMember]
[ForeignKey("AID")]
[IgnoreDataMember]
public virtual AExtensionDC AExtension { get; set; }
}
[DataContract]
[Table("AExtension")]
public class AExtensionDC
{
[DataMember]
[Key]
public string AID { get; set; }
[DataMember]
public bool? IsActive { get; set; }
public bool? IsOptedOut { get; set; }
public DateTime? LastUpdated { get; set; }
}
I am trying to use EF6 to retreive my records using DBSets in my context..
public List<ADataCcontract> GetAllAs()
{
using (AContext _aCtx = new AContext())
{
var mylist = _aCtx.A.Include("AExtension").ToList();
return mylist;
}
}
Now, I should be getting back 547 records back with only 1 of them having the AExtension navigational property having content within. The other 546 records should contain NULL. However, for some reason, I am only getting what appears to be a record that has a match in both tables. In SQL speak, I kind of just want a left join so that I return ALL rows from AE entity and OPTIONALLY matches in AE.
I hope this makes sense.
If possible, if you have a fix, could you please post an example I could referent? I am really stuck.
I think this SO Answer might get you most of the way? https://stackoverflow.com/a/4299667/78551
Basically Include does a left outer join or left join as 'outer' is actually optional in SQL.
A left join / inner join will be performed by ´.Include´ if your fields have/lack of nullability.
To review your query put a breakpoint and check this value:
var myQuery = _aCtx.A.Include("AExtension").ToTraceString();

How can I do an EF Linq query, including a subset of related entities

I have the following classes:
public class Problem
{
public Problem()
{
this.Questions = new HashSet<Question>();
this.Solutions = new HashSet<Solution>();
}
public int ProblemId { get; set; }
public string Title { get; set; }
public string Note { get; set; }
public virtual ICollection<Question> Questions { get; set; }
public virtual ICollection<Solution> Solutions { get; set; }
}
public class Question
{
public int QuestionId { get; set; }
public int ProblemId { get; set; }
public int QuestionStatusId { get; set; }
public string Note { get; set; }
public virtual Problem Problem { get; set; }
}
public class Solution
{
public int SolutionId { get; set; }
public int Number { get; set; }
public int ProblemId { get; set; }
public bool? Correct { get; set; }
public string Text { get; set; }
public string Note { get; set; }
public virtual Problem Problem { get; set; }
}
Can someone help me with LINQ for my EF6,1 SQL Server 2012.
What I would like to do is to get a List that contains only a subset of the data. In this case I would like the Notes properties in Problem, Question and Solution Entities to not be fetched from the database.
Note the Question and Solution tables are connected to the Problem table. I'm not 100% sure of this but I think this means I don't need to add an .Include.
Ideally I would like the selects that EF causes to be issues to not include the Notes column.
You can use table splitting feature of EF. Create a Problem(PK+all fields except for Notes) and a ProblemNotes(PK+Notes) entities. Then querying against Problem should satisfy your needs.
http://msdn.microsoft.com/en-us/data/jj715645.aspx
With Entity Framework table splitting you can separate the properties that might contain very large amount of data into a separate entity and only load it when required.
You might use .Select(...) to make avoid fetching redundantly data from db. The code below illustrates how to fetch list of Problems with only ProblemId and Title fields:
var result = context.Problems.Select(problem => new { ProblemId = problem.ProblemId , Title = proble.Title }).ToList();
Using of .Select above will generate SQL query "SELECT p.ProblemId,p.Title from dbo.Problems as p".
Using of .List will retrieve data (it will not be dependent on context anymore )
Your might cast resulted set to Problem type ,eg:
var newResult = result.Select(x=>new Problem() { ProblemId = x.ProblemId, Title = x.Title } )

Retrieve a list of items where an item exists in one of the items lists

Please excuse the slightly confusing title. I have a model (Project) which contains a list of items (Users).
I would like to retrieve all of the projects, where the current user is a member of the user list for that project.
I've tried:
List<Project> _MemberProjects =
_Db.Projects.Where(p =>
p.Users.Contains(_User)
).ToList();
This results in the following error:
Unable to create a constant value of type 'Nimble.Models.UserAccount'. Only primitive types or enumeration types are supported in this context.
User Model:
public class UserAccount
{
public int UserID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public ICollection<Project> Projects{....}
}
Project Model
public class Project
{
public int ProjectID { get; set; }
public DateTime CreatedDate { get; set; }
public string ProjectName { get; set; }
public string Owner { get; set; }
public ICollection<UserAccount> Users{...}
public ICollection<ProjectGroup> Groups{...}
}
Haven't tried this, but it might work:
List<Project> _MemberProjects =
_Db.Projects.Where(p =>
p.Users.Any(u => u.UserID == _User.UserID )
).ToList();
The problem is that you are mixing together Linq (the WHERE clause) and a non-Linq Collection operation (Contains). Try using pure Linq. #JamesBond's answer might work.
Are you querying a database? Then a JOIN might be another solution, but the exact syntax depends on how you are storing the relationship between the two tables.

Categories