Mehrdad Ghaffari Mehrdad Ghaffari - 3 months ago 15
C# Question

Join in Entity Framework returns unexpected value

I have this query

var q = from internalMaterialIssueVocherDetail in _ctx.InternalMaterialIssueVoucherDetails
where internalMaterialIssueVocherDetail.InternalMaterialIssueVoucherId == Id
join line in _ctx.Lines on internalMaterialIssueVocherDetail.LineId equals line.Id
join material in _ctx.Materials on line.Id equals material.LineId


I have 1 record in
InternalMaterialIssueVoucherDetails
and this table has a relation with
material
using
Lines
. In my
material
table I have 20 records, and the output is repeated 20 times with the same value.

Why? How can I solve that?

Here is the main query

var q = from internalMaterialIssueVocherDetail in _ctx.InternalMaterialIssueVoucherDetails
where internalMaterialIssueVocherDetail.InternalMaterialIssueVoucherId == Id
join line in _ctx.Lines on internalMaterialIssueVocherDetail.LineId equals line.Id
join joint in _ctx.Joints on internalMaterialIssueVocherDetail.JointId equals joint.Id
join sheet in _ctx.Sheets on joint.SheetId equals sheet.Id
join material in _ctx.Materials on line.Id equals material.LineId
//join materialDescription in _ctx.MaterialDescriptions on material.MaterialDescriptionId equals materialDescription.Id
join testPackageJoint in _ctx.TestPackageJoints on joint.Id equals testPackageJoint.JointId
join testPackage in _ctx.TestPackages on testPackageJoint.TestPackageId equals testPackage.Id
select new ViewIMIV()
{
// ItemCode = materialDescription.ItemCode,
// MaterialDescription = materialDescription.Description,
SheetNumber = sheet.SheetNumber,
LineNumber = line.LineNumber,
TestPackageNumber = testPackage.PackageNumber,
QuantityDeliverToMember = internalMaterialIssueVocherDetail.QuantityDeliverToMember.ToString(),
//Size = materialDescription.Size1
};

Answer

You can use Distinct to remove duplicates:

(from ........
select new
{
    ItemCode = materialDescription.ItemCode,
    MaterialDescription = materialDescription.Description,
    SheetNumber = sheet.SheetNumber,
    LineNumber = line.LineNumber,
    TestPackageNumber = testPackage.PackageNumber,
    QuantityDeliverToMember = internalMaterialIssueVocherDetail.QuantityDeliverToMember.ToString(),
    Size = materialDescription.Size1
}).Distinct().Select(x => new ViewIMIV()
{
    ItemCode = x.ItemCode,
    MaterialDescription = x.MaterialDescription,
    SheetNumber = x.SheetNumber,
    LineNumber = x.LineNumber,
    TestPackageNumber = x.TestPackageNumber,
    QuantityDeliverToMember = x.QuantityDeliverToMember,
    Size = x.Size
}).ToList();
Comments