Create a query using LINQ to entities with 1:N relation - c#

I know it's not something unusual to make such kind of queries but I think I get lost so I seek help. I have to tables with relation 1:N and to make it more clear I'll post a print screen from the management studio :
I am working on a asp.net mvc 3 project and I need to make a view where all Documents will be shown (and some filter and stuff, but I think that is irrelevant for this case). I need the data from the table Documents and only one specific record for each document from the DocumentFields table. This record is the record holding the name of the Document and it's uniqueness is DocumentID == Docmuents.Id, DocumentFields.RowNo == 1 and DocumentsFields.ColumnNo == 2. This is unique record for every Document and I need to get the FieldValue from this record which actually holds the Name of the Document.
I am not very sure how to build my query (maybe using JOIN) and I also would like to make my view strongly typed passing a model of type Documents but I'm not sure if it's possible, but I think depending on the way the query is build will determine the type of the model for the view.

I believe what you want is something like this:
var results =
from d in dbContext.Documents
join df in dbContext.DocumentFields
on new { d.Id, RowNo = 1, ColumnNo = 2 } equals
new { Id = df.DocumentId, df.RowNo, df.ColumnNo }
select new
{
Document = d,
DocumentName = df.FieldValue
};
Of course if you set up navigation properties, you can just do this:
var results =
from d in dbContext.Documents
let df = d.DocumentFields.First(x => x.RowNo == 1 && x.ColumnNo == 2)
select new
{
Document = d,
DocumentName = df.FieldValue
};

Related

Value on model and table keeps turning up as null

I have a table called PCRStatusLog with a column called PromoteDate. This column is fed a date where data from an excel sheet was sent from staging to the primary database. It's a new column, hasn't been used yet so for most records it is null, but we need to display the data of this column to our webapp. Most of the logic to do so already exists and the models are ADO.NET entity models generated from EF Designer From Data Base in Visual Studio.
In the table, PromoteDate is DATETIME and nullable (SQL Server) and the model for the table looks like this:
public partial class PCRStatusLog
{
// ... list of fields and properties
public Nullable<System.DateTime> PromoteDate { get; set; }
}
And was generated code, not entered manually. There's nothing special about that class, it's only a list of getters/setters that map to a table, a typical simple entity model.
Here is where it is used (I didn't write most of this code, I only added changes concerning the PromoteDate):
public List<PCRTracking> GetPCRTrackingDetails()
{
//...
List<PCRTracking> pcrDetails = (from bulk in providerMasterContext.BULK_UPLOADS
join ps in providerMasterContext.PROCESSSTATUS on bulk.ProcessStatusID equals ps.ProcessStatusID
join p in providerMasterContext.PLANs on bulk.PlanCode equals p.PlanCode
where bulk.CreateDate > compDateTime
orderby bulk.BulkUploadID descending
select new PCRTracking
{
FileID = bulk.BulkUploadID,
FileName = bulk.BulkUploadActualFileName,
PlanName = p.PlanCode,
FileStatus = string.Empty,
RecordsSubmitted = 0,
RecordsFailed = 0,
ValidationStatusReports = string.Empty,
ErrorMessage = string.Empty,
Submitter = bulk.SubmissionByID,
SubmitterName = bulk.SubmissionByName,
SubmitDate = (DateTime)bulk.SubmissionDateTime
}).ToList<PCRTracking>();
foreach (PCRTracking item in pcrDetails)
{
var promoteDateQuery = (from psl in providerMasterContext.PCRStatusLogs
where psl.BulkUploadID == item.FileID
select psl).FirstOrDefault();
item.PromoteDate = promoteDateQuery.PromoteDate;
//... rest of the code doesn't make use of PromoteDate
All of the other fields in PCRTracking object work fine, but PromoteDate keeps coming up as null, even on the one record that I manually edited to have a date.
Even here, where I examine the object returned by querying the one record I know has a date under promote date, it turns out null:
// from the Main method of a test console project
var providerMasterContext = new BulkPCRDAL().providerMasterContext;
var query =(from psl in providerMasterContext.PCRStatusLogs
where psl.BulkUploadID == 43
select psl).FirstOrDefault();
foreach(var prop in query.GetType().GetProperties())
{
Console.WriteLine(prop.GetValue(query));
}
Console.ReadLine();
It grabs all the properties on the object, and everything looks right, and matches whats in the database, except this one PromoteDate property.
Am I missing something?
Note that everything else in this model works, all other fields display data from the db, this one field is the only one that won't work.

How to get record form a different table based on a value from first table with linq expression?

I am not sure on linq for thisHow to get record from other table based on a value from first table with linq expression.
public IQueryable GetAllMeeting()
{
var allMeeting = from xx in _dbContext.tbl_Meeting
select new Meeting
{
Meeting_Attendee_Id = xx.Attendees,
Meeting_Agenda = xx.Agenda,
Meeting_Date = xx.Date,
Id = xx.Id,
Meeting_Subject = xx.Subject,
CreatedById = xx.Created_By
};
var meetingCreatedBy = _dbContext.tbl_User.SingleOrDefault(x=>x.Id == allMeeting.Creaated)
return allMeeting; // not sure if same thing can be done while fatching allMeetings or need to do a separate?
}
You can use let clause See Microsoft Docs
public IQueryable GetAllMeeting()
{
var allMeeting = from xx in _dbContext.tbl_Meeting
let meetingCreatedBy = _dbContext.tbl_User.FirstOrDefault(x=>x.Id == xx.CreatedById)
select new Meeting
{
Meeting_Attendee_Id = xx.Attendees,
Meeting_Agenda = xx.Agenda,
Meeting_Date = xx.Date,
Id = xx.Id,
Meeting_Subject = xx.Subject,
CreatedById = xx.Created_By,
CreatedBy = meetingCreatedBy !=null ? meetingCreatedBy.Name : "" //Or whatever property/column you have for displaying the name
};
return allMeeting;
}
Note: If these two tables are related with each other and the relationships are properly defined i.e. Created_By of table tbl_Meeting is connected with Id of tbl_User .You can simply use the navigation property to retrieve the user who created the meeting (i.e. xx.tbl_User.Name) . I would strongly recommend reading navigation properties and relationships
You need to perform join operation (probably left join) between two entities. Also add the required property inside model objec and return the value.

LINQ Query Not Returning one value that should be there

In a block of code I have a Foreach that I use to run through and count specific pieces that may or may not exist in the database. Basically for each part on an Order, I go on to count the Product Groups those belong to and then the Division those Product Groups belong to. For that I use this LINQ query:
foreach (var OrderDtl_yRow in ( from ThisOrderDtl in Db.OrderDtl
join ThisProdGrup in Db.ProdGrup on
ThisOrderDtl.ProdCode equals ThisProdGrup.ProdCode
where
ThisOrderDtl.Company == Session.CompanyID &&
ThisOrderDtl.OrderNum == 195792
select new
{
ProdCode = ThisOrderDtl.ProdCode,
Division = ThisProdGrup.Division_c,
OrderNum = ThisOrderDtl.OrderNum,
OrderLine = ThisOrderDtl.OrderLine
}))
{ ....counting things... }
Currently I've got message boxes set up to return the values to me as the process is going. I get everything to return correctly except the Division, that always shows up as blank in the MessageBoxes (So NULL I'd assume). So my Counters for Division don't Increment.
If I take that out into LINQPad I'm unsure how to return results of a foreach, but I tried it with
if(OrderDtl_yRow.Division != null && OrderDtl_yRow.Division != "")
{i++;}
i.Dump();
and got 5 (There were 5 rows I expected so I'm at least pulling our something). Then I converted it to a simpler FirstOrDefault statement to test a single value like
var OrderDtl_yRow = ( from ThisOrderDtl in OrderDtl
join ThisProdGrup in ProdGrup on
ThisOrderDtl.ProdCode equals ThisProdGrup.ProdCode
where
ThisOrderDtl.OrderNum == 195792 &&
ThisOrderDtl.OrderLine == 1
select new
{
ProdCode = ThisOrderDtl.ProdCode,
Division = ThisProdGrup.Division_c,
OrderNum = ThisOrderDtl.OrderNum,
OrderLine = ThisOrderDtl.OrderLine
}).FirstOrDefault();
Then if I do a OrderDtl_yRow.Dump() I get my result and sure enough, Division comes through. So all signs point to it being fine, yet I can't bring over the value where I actually need it to show up. Thoughts? Thanks!
P.S. For those familiar with Epicor ERP Division is a UD field, so it technically belongs to the table ProdGrup_UD, but in Epicor it recognized that as the table ProdGrup just fine, its only SQL that makes you join _UD to the parent table. I tried joining it anyways for funsies and it didn't like it because it knew the column was there already. So that should be fine.
UPDATE: Rookie Move, didn't upload the Division data into the testing environment, so nothing was there, then checked against Live data where it existed and scratched my head as to why it didn't match. But I learned something about LinqPad and Linq so it wasn't a useless exercise.
You need to play some more in Linqpad to see what is happening, Set the language to C# program, Press F4 and add references to Server\Bin\Epicor.System.dll and Server\Assemblies\Erp.Data.910100.dll and point the app.copnfig to your Server\web.config file. In the main block create yourself a Db context with var Db = new Erp.ErpContext();
Linqpad can display complex data structures so you needn't have done FirstOrDefault in your last example. for instance:
void Main()
{
var Db = new Erp.ErpContext();
var sessionCompany = "EPIC06";
var x = (from hed in Db.OrderHed
join dtl in Db.OrderDtl
on new { hed.Company, hed.OrderNum }
equals new { dtl.Company, dtl.OrderNum }
into dtlList
where
hed.Company == sessionCompany
select new { hed, dtlList })
.Dump();
}
Also note that in SQL dbo.ProdGrup is an autogenerated view that joins the tables Erp.ProdGrup and Erp.ProdGrup_UD for you.

LINQ with ManyToMany: Filtering based on multiple selection

I am a newbe to C# and have to use it for my master thesis. At the moment, I am facing a problem that is a bit to complex for me.
I have set up a database with a many-to-many relationship like this:
Table Relay:
- id (PK)
- Name
- Input
Table ProtectionFunction:
- id (PK)
- ANSI
- IEC
- Description
Table RelayConfig (junction table)
- RelayID (PK)
- ProtFuncID (PK)
- TimeToSaturate
- Remanence
The thing is, a Relay can have multiple protection functions, and for each it has specific values for TimeToSaturate and Remanence. Now I want to realize a filter. The user can select protection function via checkboxes in a DataGridView and a ListBox should show all Relays that support ALL of these protection functions.
I have already created the LINQ-to-SQL classes for my project. But now I am stuck because I don't know how to realize the filtering. All LINQ commands I have found so far would give me all Relays for one protection function.
I really hope one of you can give me a hint.
var ids = new int[]{ ... };
// if ids is null or ids.Length == 0 please return null or an empty list,
//do not go further otherwise you'll get Relays without any function filter
var query = Relays.AsQueryable();
foreach (var id in ids)
{
var tempId = id;
query = query.Where(r=>r.RelayConfigs.Any(rc=>rc.ProtFuncID == tempId));
}
var items = query.ToList();
Update
Just saw this on PredicateBuilder page:
The temporary variable in the loop is required to avoid the outer
variable trap, where the same variable is captured for each iteration
of the foreach loop.
It's easier if you start from the RelayConfigs. Something like this should work:
var protFuncIds = new[]{1,2,3};
var query = from rc in db.RelayConfigs
where protFuncIds.Contains(rc.ProtFuncID)
select rc.Relay;
var relays = query.Distinct().ToList();
UPDATE:
based on your comment, the following should work, however do monitor the SQL generated...
IQueryable<Relay> query = db.Relays
foreach (var id in ids)
query = relays.Where(r => r.RelayConfigs.Select(x => x.ProtFuncId).Contains(id));
var relays = query.ToList();
// Build a list of protection function ids from your checkbox list
var protFuncIDs = [1,2,3,4];
using(var dc = new MyDataContext())
{
var result = dc.Relays.Where(r=>protFuncIDs.Join(r.RelayConfigs, pf=>pf, rc=>rc.ProtFuncID, (pf,rc)=>pf).Count() == protFuncIDs.Length).ToArray();
}
It's not especially efficient, but that should do the trick for you.
I have done this in Lightswitch, and here was my preprocess query:
partial void UnusedContactTypesByContact_PreprocessQuery(int? ContactID, ref IQueryable<ContactType> query)
{
query = from contactType in query
where !contactType.ContactToContactTypes.Any(c => c.Contact.Id == ContactID)
select contactType;
}
Hope that helps.

How do I extract this LinqToSql data into a POCO object?

with my Repository classes, I use LinqToSql to retrieve the data from the repository (eg. Sql Server 2008, in my example). I place the result data into a POCO object. Works great :)
Now, if my POCO object has a child property, (which is another POCO object or an IList), i'm trying to figure out a way to populate that data. I'm just not too sure how to do this.
Here's some sample code i have. Please note the last property I'm setting. It compiles, but it's not 'right'. It's not the POCO object instance .. and i'm not sure how to code that last line.
public IQueryable<GameFile> GetGameFiles(bool includeUserIdAccess)
{
return (from q in Database.Files
select new Core.GameFile
{
CheckedOn = q.CheckedOn.Value,
FileName = q.FileName,
GameFileId = q.FileId,
GameType = (Core.GameType)q.GameTypeId,
IsActive = q.IsActive,
LastFilePosition = q.LastFilePosition.Value,
UniqueName = q.UniqueName,
UpdatedOn = q.UpdatedOn.Value,
// Now any children....
// NOTE: I wish to create a POCO object
// that has an int UserId _and_ a string Name.
UserAccess = includeUserIdAccess ?
q.FileUserAccesses.Select(x => x.UserId).ToList() : null
});
}
Notes:
Database.Files => The File table.
Database.FilesUserAccess => the FilesUserAccess table .. which users have access to the GameFiles / Files table.
Update
I've now got a suggestion to extract the children results into their respective POCO classes, but this is what the Visual Studio Debugger is saying the class is :-
Why is it a System.Data.Linq.SqlClient.Implementation.ObjectMaterializer<..>
.Convert<Core.GameFile> and not a List<Core.GameFile> containing the POCO's?
Any suggestions what that is / what I've done wrong?
Update 2:
this is what i've done to extract the children data into their respective poco's..
// Now any children....
UserIdAccess = includeUserIdAccess ?
(from x in q.FileUserAccesses
select x.UserId).ToList() : null,
LogEntries = includeUserIdAccess ?
(from x in q.LogEntries
select new Core.LogEntry
{
ClientGuid = x.ClientGuid,
ClientIpAndPort = x.ClientIpAndPort,
// ... snip other properties
Violation = x.Violation
}).ToList() : null
I think that all you need to do is to put another Linq query in here:
q.FileUserAccesses.Select(x => x.UserId).ToList()
i.e. You want to select data from the FileUserAccess records - which I'm assuming are Linq to SQL classes, so to do this you can have something like:
(from fua in q.FileUserAccesses
select new PocoType
{
UserID = fua.UserID,
Name = fua.User.UserName // Not sure at this point where the name comes from
}).ToList()
That should get you pointed in the right direction at least.
What is the type of UserIdAccess? How is it not 'right'? Are you getting the 'wrong' data? if so have you checked your database directly to make sure the 'right' data is there?

Categories