Linq Left Outer Join C# - c#

I have been working with this linq query for a while. I have looked at a ton of answers on stackoverflow and beyond. I have tried many solutions and read up on just as many. The code below is 2 of my numerous attempts to create this inner join the error that I am getting is
Object reference not set to an instance of the object
Attempt A
var records = from cr in lstContactResponse
join jn in lstJourneyNodeData on cr.GrandparentId equals jn.Id into a
from x in a.DefaultIfEmpty()
join j in lstJourney on x.JourneyId equals j.Id into b
from y in b.DefaultIfEmpty()
join ce in lstCampaignElement on y.Name equals ce.LinkedJourney into c
from z in c.DefaultIfEmpty()
join c in lstCampaign on z.CampaignId equals c.Id into d
from w in d.DefaultIfEmpty()
select new JourneyRecord
{
CompanyName = w.Company,
BrandName = w.Brand,
CampaignName = w.Name,
Channel = z.Type,
Wave = "",
CampaignId = w.Id,
ActivityDate = cr.ResponseDate,
Activity = "",
Unsubscribed = cr.Unsubscribed,
Responded = cr.Responded,
Clicked = cr.Clicked,
Viewed = cr.Viewed,
Sent = cr.Sent,
Targeted = cr.Targeted,
HardBounced = cr.HardBounced,
SoftBounced = cr.SoftBounced,
WasTargeted = cr.WasTargeted,
Email = "",
Id = "",
CampaignElementId = z.Id,
CampaignWaveId = "J" + x.Id,
ContactId = cr.ContactId,
AtTaskId = w.AtTaskId,
LinkClicked = cr.Referrer,
OptTopic = z.TopicId,
DiseaseState = "",
ElementDescription = y.Name,
WaveDescription = x.Label
};
Attempt B
var records = from cr in lstContactResponse
join jn in lstJourneyNodeData on cr.GrandparentId equals jn.Id into a
from x in a.DefaultIfEmpty()
join j in lstJourney on x.JourneyId equals j.Id into b
from y in b.DefaultIfEmpty()
join ce in lstCampaignElement on y.Name equals ce.LinkedJourney into c
from z in c.DefaultIfEmpty()
join c in lstCampaign on z.CampaignId equals c.Id into d
from w in d.DefaultIfEmpty()
select new JourneyRecord
{
CompanyName = x == null ? null : w.Company,
BrandName = x == null ? null : w.Brand,
CampaignName = x == null ? null : w.Name,
Channel = x == null ? null : z.Type,
Wave = "",
CampaignId = x == null ? null : w.Id,
ActivityDate = x == null ? null : cr.ResponseDate,
Activity = "",
Unsubscribed = x == null ? null : cr.Unsubscribed,
Responded = x == null ? null : cr.Responded,
Clicked = x == null ? null : cr.Clicked,
Viewed = x == null ? null : cr.Viewed,
Sent = x == null ? null : cr.Sent,
Targeted = x == null ? null : cr.Targeted,
HardBounced = x == null ? null : cr.HardBounced,
SoftBounced = x == null ? null : cr.SoftBounced,
WasTargeted = x == null ? null : cr.WasTargeted,
Email = "",
Id = "",
CampaignElementId = x == null ? null : z.Id,
CampaignWaveId = "J" + (x == null ? null : x.Id),
ContactId = x == null ? null : cr.ContactId,
AtTaskId = x == null ? null : w.AtTaskId,
LinkClicked = x == null ? null : cr.Referrer,
OptTopic = x == null ? null : z.TopicId,
DiseaseState = "",
ElementDescription = x == null ? null : y.Name,
WaveDescription = x == null ? null : x.Label
};
Attempt C
var records = from cr in lstContactResponse
join jn in lstJourneyNodeData on cr.GrandparentId equals jn.Id into a
from x in a.DefaultIfEmpty()
join j in lstJourney on x.JourneyId equals j.Id into b
from y in b.DefaultIfEmpty()
join ce in lstCampaignElement on y.Name equals ce.LinkedJourney into c
from z in c.DefaultIfEmpty()
join c in lstCampaign on z.CampaignId equals c.Id into d
from w in d.DefaultIfEmpty()
select new JourneyRecord
{
CompanyName = w == null ? null : w.Company,
BrandName = w == null ? null : w.Brand,
CampaignName = w == null ? null : w.Name,
Channel = z == null ? null : z.Type,
Wave = "",
CampaignId = w == null ? null : w.Id,
ActivityDate = cr == null ? null : cr.ResponseDate,
Activity = "",
Unsubscribed = cr == null ? null : cr.Unsubscribed,
Responded = cr == null ? null : cr.Responded,
Clicked = cr == null ? null : cr.Clicked,
Viewed = cr == null ? null : cr.Viewed,
Sent = cr == null ? null : cr.Sent,
Targeted = cr == null ? null : cr.Targeted,
HardBounced = cr == null ? null : cr.HardBounced,
SoftBounced = cr == null ? null : cr.SoftBounced,
WasTargeted = cr == null ? null : cr.WasTargeted,
Email = "",
Id = "",
CampaignElementId = z == null ? null : z.Id,
CampaignWaveId = "J" + (x == null ? null : x.Id),
ContactId = cr == null ? null : cr.ContactId,
AtTaskId = w == null ? null : w.AtTaskId,
LinkClicked = cr == null ? null : cr.Referrer,
OptTopic = z == null ? null : z.TopicId,
DiseaseState = "",
ElementDescription = y == null ? null : y.Name,
WaveDescription = x == null ? null : x.Label
};

Of course there is a way to do that in LINQ. If you have answered my questions in the comment, I would provide you the exact solution, now I'll just give you an example. The technique is different for LINQ to Objects vs LINQ to Entities, so the following apply for LINQ to Objects.
The solution is to check for null every property involved in the right side of the left join, including the further joins. Also value type properties needs to be converted to nullable (that's why it was important to have your classes - for prior C#6 code).
Here is the example:
Having the following "tables"
var t1 = new[]
{
new { Id = 1 , Name = "A", Date = DateTime.Today },
new { Id = 2 , Name = "B", Date = DateTime.Today},
new { Id = 3 , Name = "C", Date = DateTime.Today},
};
var t2 = new[]
{
new { Id = 1 , ParentId = 1, Name = "A1", Date = DateTime.Today },
new { Id = 2 , ParentId = 2, Name = "B1", Date = DateTime.Today },
};
var t3 = new[]
{
new { Id = 1 , ParentId = 1, Name = "A11", Date = DateTime.Today },
new { Id = 2 , ParentId = 1, Name = "A12", Date = DateTime.Today },
};
var t4 = new[]
{
new { Id = 1 , ParentId = 1, Name = "A111", Date = DateTime.Today },
};
Pre C#6
var query =
from e1 in t1
join e2 in t2 on e1.Id equals e2.ParentId into g2
from e2 in g2.DefaultIfEmpty()
join e3 in t3 on e2 != null ? (int?)e2.Id : null equals e3.ParentId into g3
from e3 in g3.DefaultIfEmpty()
join e4 in t4 on e3 != null ? (int?)e3.Id : null equals e4.Id into g4
from e4 in g4.DefaultIfEmpty()
select new
{
t1_Id = e1.Id,
t1_Name = e1.Name,
t1_Date = e1.Date,
t2_Id = e2 != null ? (int?)e2.Id : null,
t2_Name = e2 != null ? e2.Name : null,
t2_Date = e2 != null ? (DateTime?)e2.Date : null,
t3_Id = e3 != null ? (int?)e3.Id : null,
t3_Name = e3 != null ? e3.Name : null,
t3_Date = e3 != null ? (DateTime?)e3.Date : null,
t4_Id = e4 != null ? (int?)e4.Id : null,
t4_Name = e4 != null ? e4.Name : null,
t4_Date = e4 != null ? (DateTime?)e4.Date : null,
};
var result = query.ToList();
Looks ugly, but works.
C#6 - The same result is achieved by simply adding ? before any right side property accessor (repeat - including join conditions)
var query =
from e1 in t1
join e2 in t2 on e1.Id equals e2.ParentId into g2
from e2 in g2.DefaultIfEmpty()
join e3 in t3 on e2?.Id equals e3.ParentId into g3
from e3 in g3.DefaultIfEmpty()
join e4 in t4 on e3?.Id equals e4.Id into g4
from e4 in g4.DefaultIfEmpty()
select new
{
t1_Id = e1.Id,
t1_Name = e1.Name,
t1_Date = e1.Date,
t2_Id = e2?.Id,
t2_Name = e2?.Name,
t2_Date = e2?.Date,
t3_Id = e3?.Id,
t3_Name = e3?.Name,
t3_Date = e3?.Date,
t4_Id = e4?.Id,
t4_Name = e4?.Name,
t4_Date = e4?.Date,
};
var result = query.ToList();

There was no way with Linq that I was able to determine to accomplish what I had wanted to do. Therefore I went another direction with the solution to the problem.
foreach (ContactResponse cr in lstContactResponse)
{
ContactResponseRecord crr = new ContactResponseRecord() {
ContactId = cr.ContactId,
ActivityDate = cr.ResponseDate,
LinkClicked = cr.Referrer};
var vJourneyNodeData = from x in lstJourneyNodeData where x.Id == cr.GrandparentId select x;
if(null != vJourneyNodeData && vJourneyNodeData.Count() > 0)
{
jnd = vJourneyNodeData.FirstOrDefault();
crr.CampaignWaveId = "J" + jnd.Id;
crr.WaveDescription = jnd.Label;
}
var vJourney = from x in lstJourney where x.Id == jnd.JourneyId select x;
if (null != vJourney && vJourney.Count() > 0)
{
j = vJourney.FirstOrDefault();
crr.OptTopic = j.TopicId;
}
var vCampaignElement = from x in lstCampaignElement where x.LinkedJourney == j.Name select x;
if (null != vCampaignElement && vCampaignElement.Count() > 0)
{
ce = vCampaignElement.FirstOrDefault();
crr.Ccg_Id = ce.CCGId;
crr.ElementDescription = ce.Description.ToString();
crr.CampaignElementId = ce.Id;
var vCampaign = from x in lstCampaign where x.Id == ce.CampaignId select x;
if (null != vCampaign && vCampaign.Count() > 0)
{
c = vCampaign.FirstOrDefault();
crr.ActivityDate = c.AtTaskId;
crr.BrandName = c.Brand;
crr.CampaignId = c.Id;
crr.CampaignName = c.Name;
crr.CompanyName = c.Company;
}
}

Related

EF Core Linq join on multiple columns throws NullReference Exception

I have a rather ugly query that just had to be expanded by one more join. The query builds then throws a NullReferenceException runtime. As I'm struggling around the exception details I found the message at TargetSite/CustomAttributes/Message = "The method or operation is not implemented." But I don't know which method?
MarkedItems is the new join and I think the problem could be the join on multiple columns or that I had to add the new table into the group by clause. The same query runs in LinqPad with EF6, so this must be something that hasn't been implemented in EF7 yet.
EF Core version is 1.1.2.
The query:
var inventory = (from it in _ctx.Items
join i in _ctx.Inventories on it.Id equals i.ItemId into iit
from i in iit.DefaultIfEmpty()
join m in _ctx.MarkedItems on
new {
eancode = i.EANCode,
projectid = i.ProjectId
}
equals new {
eancode = (m != null ? m.EANCode : string.Empty),
projectid = (m != null ? m.ProjectId : Guid.Empty)
} into im
from m in im.DefaultIfEmpty()
where it.ProjectId == cmp.ProjectId
group i by new {
EANCode = it.EANCode,
ItemNo = it.ItemNo,
Name = it.Name,
BaseQty = it.BaseQty,
Price = it.Price,
m = (m != null ? m.EANCode : null)
} into lg
select new ComparisonBaseModel() {
EANCode = lg.Key.EANCode,
ItemName = lg.Key.Name,
Price = lg.Key.Price,
ScanQty = lg.Sum(s => s != null ? s.ScanQty : 0),
BaseQty = lg.Key.BaseQty,
DiffQty = lg.Sum(s => s != null ? s.ScanQty : 0) - lg.Key.BaseQty,
DiffPrice = lg.Key.Price * (lg.Sum(s=> s!= null ? s.ScanQty : 0) - lg.Key.BaseQty),
AllTasked = !lg.Any(s=>(s != null && s.InventoryTaskId == null) || s==null),
Flagged = lg.Key.m != null
}).Where(x=>x.DiffQty != 0);
Thanks to the comments I was able to find out the real problem with my query. I hadn't realized before, that Inventories (i) could be null, too, so I had to check for nulls even the i-s (not only m-s) in MarketItems join.
Not sure if this could be helpful to anyone but the error message was misleading after I have already run into some EF7/EF6 differences.
var inventory = (from it in _ctx.Items
join i in _ctx.Inventories on it.Id equals i.ItemId into iit
from i in iit.DefaultIfEmpty()
join m in _ctx.MarkedItems on
new {
eancode = (i != null ? i.EANCode : string.Empty),
projectid = (i != null ? i.ProjectId : Guid.Empty)
}
equals new {
eancode = (m != null ? m.EANCode : string.Empty),
projectid = (m != null ? m.ProjectId : Guid.Empty)
} into im
from m in im.DefaultIfEmpty()
where it.ProjectId == cmp.ProjectId
group i by new {
EANCode = it.EANCode,
ItemNo = it.ItemNo,
Name = it.Name,
BaseQty = it.BaseQty,
Price = it.Price,
m = (m != null ? m.EANCode : null)
} into lg
select new ComparisonBaseModel() {
EANCode = lg.Key.EANCode,
ItemName = lg.Key.Name,
Price = lg.Key.Price,
ScanQty = lg.Sum(s => s != null ? s.ScanQty : 0),
BaseQty = lg.Key.BaseQty,
DiffQty = lg.Sum(s => s != null ? s.ScanQty : 0) - lg.Key.BaseQty,
DiffPrice = lg.Key.Price * (lg.Sum(s=> s!= null ? s.ScanQty : 0) - lg.Key.BaseQty),
AllTasked = !lg.Any(s=>(s != null && s.InventoryTaskId == null) || s==null),
Flagged = lg.Key.m != null
}).Where(x=>x.DiffQty != 0);

C# - Using Linq get data if null value exist in query

I have two datatables,
var userList1 = from myRow in dt.AsEnumerable()
where myRow.Field<bool?>("IsActive1") == null
? true
: myRow.Field<bool?>("IsActive1") == true
select myRow;
var userList2 = from myRow in dt1.AsEnumerable()
select myRow;
dt1 table shows like this,
Using this Linq query,
var objUserSetUp1 = (from A in userList1
join B in userList2
on new
{
UserId = A.Field<Int64?>("Id") == null
? 0
: A.Field<Int64>("Id")
}
equals new
{
UserId = B.Field<Int64?>("UserId") == null
? 0
: B.Field<Int64>("UserId")
}
select new
{
UserId = A.Field<Int64>("Id"),
FirstName = A.Field<string>("FirstName"),
SurName = A.Field<string>("SurName"),
Computer_Name = A.Field<string>("Computer_Name"),
IP_Address = A.Field<string>("IP_Address"),
LogInTime = A.Field<string>("LogInTime") == null
? "UnKnown"
: A.Field<string>("LogInTime"),
UserName = A.Field<string>("UserName"),
Password = A.Field<string>("Password"),
login_Id = A.Field<Int64?>("login_Id") == null
? 0 :
A.Field<Int64?>("login_Id"),
docCount = B.Field<Int64>("docCount")
}).ToList();
How can I get if UserId is null also want to take docCout field value too. How can I do this inside the query?
I think you need a Left Outer Join, where the default value for the outer join (ie when no matching record exists) is the userList2 entry where Field("UserId") is null.
See below (untested, but you get the idea!):
var objUserSetUp1 = (from A in userList1
join B in userList2
on A.Field<Int64?>("Id") equals B.Field<Int64?>("UserId")
into BGroup
from C in BGroup.DefaultIfEmpty(userList2.Single(u => u.Field<Int64?>("UserId") == null))
select new
{
UserId = A.Field<Int64>("Id"),
FirstName = A.Field<string>("FirstName"),
SurName = A.Field<string>("SurName"),
Computer_Name = A.Field<string>("Computer_Name"),
IP_Address = A.Field<string>("IP_Address"),
LogInTime = A.Field<string>("LogInTime") == null
? "UnKnown"
: A.Field<string>("LogInTime"),
UserName = A.Field<string>("UserName"),
Password = A.Field<string>("Password"),
login_Id = A.Field<Int64?>("login_Id") == null
? 0 :
A.Field<Int64?>("login_Id"),
docCount = C.Field<Int64>("docCount")
}).ToList();

Union Two Linq Queries

I have two LinqToSql queries that return result sets:
var grResults = (from g in ctx.GeneralRequests
join rt in ctx.RequestTypes on g.RequestTypeId equals rt.RequestTypeId
join sub in ctx.Logins on g.SubmitterStaffId equals sub.LoginId
join onb in ctx.Logins on g.OnBehalfOfStaffId equals onb.LoginId
where sub.GadId == gadId
select new
{
Status = "Submitted",
RequestId = g.GeneralRequestId,
Submitter = sub.UserName,
OnBehalf = (onb == null ? string.Empty : onb.UserName),
RequestType = (rt == null ? string.Empty : rt.Description),
ProjectName = (g == null ? string.Empty : g.ProjectName) ,
Comments = (g == null ? string.Empty : g.Comments),
LastUpdate = g.LastUpdateDate
});
var grdResults = (from gd in ctx.GeneralRequestDrafts
join rt in ctx.RequestTypes on gd.RequestTypeId equals rt.RequestTypeId
into tempRequestTypes
from rt1 in tempRequestTypes.DefaultIfEmpty()
join onb in ctx.Logins on gd.OnBehalfOfStaffId equals onb.LoginId
into tempOnBehalf
from onb1 in tempOnBehalf.DefaultIfEmpty()
join sub in ctx.Logins on gd.SubmitterStaffId equals sub.LoginId
where sub.GadId == gadId
select new
{
Status = "Draft",
RequestId = gd.GeneralRequestDraftId,
Submitter = sub.UserName,
OnBehalf = (onb1 == null ? string.Empty : onb1.UserName),
RequestType = (rt1 == null ? string.Empty : rt1.Description),
ProjectName = (gd.ProjectName == null ? string.Empty : gd.ProjectName),
Comments = (gd.Comments == null ? string.Empty : gd.Comments),
LastUpdate = gd.LastUpdateDate
});
The problem is when I try to Union them.
var results = grResults.Union(grdResults).OrderByDescending(r => r.LastUpdate);
This returns no records even though the two individual queries do.
Since the 2 queries don't appear to rely on each other just execute both and union the results of each if you are just trying to get a single list.
var results = grResults.ToList().Union(grdResults.ToList())
.OrderByDescending(r => r.LastUpdate);

How to check null while joining multiple tables by LINQ?

var Data = (from s in _context.PRD_RecipeItem.AsEnumerable()
where s.RecipeID == _RecipeID
from i in _context.Sys_ChemicalItem.Where(x => x.ItemID == s.ItemID).DefaultIfEmpty()
from u in _context.Sys_Unit.Where(x => x.UnitID == s.UnitID).DefaultIfEmpty()
from st in FinalStock.AsEnumerable().Where(x => x.ItemID == s.ItemID).DefaultIfEmpty()
from sup in _context.Sys_Supplier.Where(x => x.SupplierID == (st==null? 0: st.SupplierID)).DefaultIfEmpty()
select new PRDChemProdReqItem
{
ItemID = s.ItemID,
ItemName = (i == null ? null : i.ItemName),
RequiredQty = s.RequiredQty,
RequiredUnit = s.UnitID,
RequiredUnitName = (u == null ? null : u.UnitName),
RequsitionQty = s.RequiredQty,
ApproveQty = s.RequiredQty,
ApproveUnit = s.UnitID,
ApproveUnitName = (u == null ? null : u.UnitName),
PackSizeName = "",
PackQty = 0,
SizeUnitName = "",
RequisitionUnit = s.UnitID,
RequisitionUnitName = (u == null ? null : u.UnitName),
StockQty = (st == null ? null : (Math.Round(Convert.ToDecimal(st.ClosingQty), 2)).ToString()),
SupplierID = (st == null ? 0 : st.SupplierID),
SupplierName = (sup == null ? null : sup.SupplierName),
ItemSource = "Via Requisition"
}).ToList();
This is my code. When st is null, then I'm getting An exception of type System.Reflection.TargetException. How to solve this issue. Thanks in Advance.
Why don't you use join? This will take care of your null values.
See more details including source code here: http://msdn.microsoft.com/en-us/library/bb311040.aspx

unit test failed but LINQ query is returning result in Linq Pad and in Program too

Hi i am writing a query to my Database to get some records using left join and group by and hence i am getting some objects with null value, that is creating problem
below is my query
var cards = from classCreative in _unitOfWork.ClassCreatives.All
join trainer in _unitOfWork.UserCoreDetails.All on classCreative.RegistrationId equals
trainer.Id
join imageData in
(
from imag in
(from cci in _unitOfWork.ClassCreativeImages.All
group cci by cci.ClassCreativeId
into images
select new { ClassCreativeId = images.Key, MinImageId = images.Min(arg => arg.Id) })
join i in _unitOfWork.ClassCreativeImages.All
on imag.MinImageId equals i.Id
select new { imag.ClassCreativeId, i.FileName, i.Title }
) on classCreative.Id equals imageData.ClassCreativeId into classCreativeImages
from classImage in classCreativeImages.DefaultIfEmpty()
join classBatchTicketVenue in
(
from batchTicket in
(from batch in _unitOfWork.Batches.All
join ticket in _unitOfWork.Tickets.All on batch.ClassScheduleId equals
ticket.ClassScheduleId
where batch.StartDate > DateTime.Now
group new { ticket = ticket, batch = batch } by new { batch.ClassCreativeId }
into batchTicketGrouping
select new
{
batchTicketGrouping.Key.ClassCreativeId,
MinVenueId = batchTicketGrouping.Min(arg => arg.batch.VenueId),
MaxNoOfSesssions = batchTicketGrouping.Max(arg => arg.batch.TotalNoOfSessions),
MinNoOfSesssions = batchTicketGrouping.Min(arg => arg.batch.TotalNoOfSessions),
StartDate = batchTicketGrouping.Min(arg => arg.batch.StartDate),
MinPrice = batchTicketGrouping.Min(arg => arg.ticket.Price),
VenueCount = batchTicketGrouping.Select(arg => arg.batch.VenueId).Distinct().Count()
})
join venue in _unitOfWork.Venues.All on batchTicket.MinVenueId equals venue.Id
select new
{
batchTicket.MaxNoOfSesssions,
batchTicket.MinNoOfSesssions,
batchTicket.MinPrice,
batchTicket.MinVenueId,
batchTicket.StartDate,
batchTicket.VenueCount,
venue.LocalityId,
venue.CityId,
batchTicket.ClassCreativeId
}
) on classCreative.Id equals classBatchTicketVenue.ClassCreativeId into classCards
from batchVenueTicketData in classCards.DefaultIfEmpty()
select new
ClassCard
{
Title = classCreative.Title,
Firstname = trainer.FirstName,
LastName = trainer.LastName,
Id = classCreative.Id,
TrainerId = trainer.Id,
MaxSessionCount = batchVenueTicketData.ClassCreativeId == null ? null : (int?) batchVenueTicketData.MaxNoOfSesssions,
MinSessionCount = batchVenueTicketData.ClassCreativeId == null ? null : (int?) batchVenueTicketData.MinNoOfSesssions,
MinPrice = batchVenueTicketData.ClassCreativeId == null ? null : (decimal?) batchVenueTicketData.MinPrice,
StartDate = batchVenueTicketData.ClassCreativeId == null ? null : (DateTime?) batchVenueTicketData.StartDate,
VenueCount = batchVenueTicketData.ClassCreativeId == null ? 0 : (int?) batchVenueTicketData.VenueCount,
CityId = batchVenueTicketData.ClassCreativeId == null ? null : (int?) batchVenueTicketData.CityId,
LocaltyId = batchVenueTicketData.ClassCreativeId == null ? null : (int?) batchVenueTicketData.LocalityId,
FileName = classImage.ClassCreativeId == null ? null : classImage.FileName,
ImageAlt = classImage.ClassCreativeId == null ? null : classImage.Title
}
this query is working fine but its unit test is failing
given below is unit test for it
[TestMethod]
[Isolated]
public void ClassCardAll_Test_Must_Return_All_ClassCards()
{
var searchContext = Isolate.Fake.AllInstances<SearchContext>();
var loggger = Isolate.Fake.Instance<ILogger>(Members.ReturnRecursiveFakes);
var searchAccesor = new SearchAccessor(new SearchUnitOfWork(new SearchContext()), new TypeMapperService(),
loggger, new CacheService());
Isolate.WhenCalled(() => searchContext.ClassCreatives)
.WillReturn(new FakeClassCreativeSearchDbSet(GetClassCreativeSearchCollection()));
Isolate.WhenCalled(() => searchContext.ClassCreativeImageSearches)
.WillReturn(new FakeClassCreativeImageSearchDbSet(GetClassCreativeImageSearchCollection()));
Isolate.WhenCalled(() => searchContext.Batches)
.WillReturn(new FakeBatchSearchDbSet(GetBatchSearchCollection()));
Isolate.WhenCalled(() => searchContext.Venues)
.WillReturn(new FakeVenueSearchDbSet(GetVenueSearchCollection()));
Isolate.WhenCalled(() => searchContext.Users)
.WillReturn(new FakeUserCoreDetailDbSet(GetUserCoreDetailCollection()));
Isolate.WhenCalled(() => searchContext.Tickets)
.WillReturn(new FakeClassTicketSearchDbSet(GetClassTicketSearchCollection()));
var classCards = searchAccesor.ClassCardAll();
Assert.AreEqual(classCards.Count,2,"classcard is mapped properly");
Assert.AreEqual(classCards[0].FileName,"file1","FlieName is not calculated");
Assert.AreEqual(classCards[0].Title, "Title1", "FlieName is not calculated");
Assert.AreEqual(classCards[0].Firstname, "FirstName", "FlieName is not calculated");
Assert.AreEqual(classCards[0].Id, 1, "id for first row is not calculated");
Assert.AreEqual(classCards[1].Id, 2, "id for 2nd wor is not calculated");
Assert.AreEqual(classCards[1].CityId, null, "city id is not calculated");
Assert.AreEqual(classCards[0].CityId, 1, "city id is not calculated");
Assert.AreEqual(classCards[1].LocaltyId, null, "location id is not calculated");
Assert.AreEqual(classCards[0].LocaltyId, 1, "location id is not calculated");
}
but when I am running this unit test it is throwing exception as below
Test method SkillKindle.BLL.Testing.Search.SearchAccessorTest.ClassCardAll_Test_Must_Return_All_ClassCards threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at lambda_method(Closure, <>f__AnonymousType19`2, <>f__AnonymousType18`9)
at System.Linq.Enumerable.<SelectManyIterator>d__31`3.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList(IEnumerable`1 source)
at SkillKindle.BLL.Search.SearchAccessor.ClassCardAll() in SearchAccessor.cs: line 290
at SkillKindle.BLL.Testing.Search.SearchAccessorTest.ClassCardAll_Test_Must_Return_All_ClassCards() in SearchAccessorTest.cs: line 500
at TypeMock.MockManager.getReturn(Object context, String typeName, String methodName, Object methodGenericParams, Boolean isDecorated, Boolean isInterceptedType, Object[] methodArguments)
at Typemock.Interceptors.Profiler.InternalMockManager.getReturn(Object that, String typeName, String methodName, Object methodParameters, Boolean isInjected, Boolean isInterceptedType)
at SkillKindle.BLL.Testing.Search.SearchAccessorTest.ClassCardAll_Test_Must_Return_All_ClassCards() in SearchAccessorTest.cs: line 0
i have done some research and i came to know if i use
VenueCount = batchVenueTicketData == null ? 0 : (int?) batchVenueTicketData.VenueCount,
instead of
VenueCount = batchVenueTicketData.ClassCreativeId == null ? 0 : (int?) batchVenueTicketData.VenueCount,
my test works fine where as my query doesnt work
please help me solving this issue, Thanks in advance

Categories