How to query MongoDB multiple digit subcollection with C# - c#

I have a multi-digit category table and I want to query the bottom category from that table.
This way I can get the first digit when I query, but it does not bring the lower digits
var query = Query<Category>.ElemMatch(x => x.SubCategories, builder => builder.EQ(actor => actor.IntegrationCategoryCode, categoryId));
var repository = new Data.MongoDB.Repository.MongoRepository<Category>();
var result= repository.CustomQuery(query).ToList();
[CollectionName("Category ")]
public class Category : Base.Entity
{
[BsonElement("CategoryId")]
public int CategoryId { get; set; }
[BsonElement("IntegrationCategoryName")]
public string IntegrationCategoryName { get; set; }
[BsonElement("IntegrationCategoryCode")]
public string IntegrationCategoryCode { get; set; }
[BsonElement("IntegrationParentCode")]
public string IntegrationParentCode { get; set; }
[BsonElement("Deleted")]
[BsonRepresentation(BsonType.Boolean)]
public bool Deleted { get; set; }
[BsonElement("CreateDate")]
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime CreateDate { get; set; }
[BsonElement("UpdateDate")]
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime UpdateDate { get; set; }
public List<Category> SubCategories { get; set; }
}

Related

Selection for Linq Query

How can I select the List of ExtrasName and ExtrasId in the following query.
The query contains some mathematical operations aswell.
var query =
from a in _context.Cities
from b in a.CityExtras
where a.CityId == CityId && extraIds.Contains(b.ExtrasId)
group new { a, b } by new { a.PricePerSqM , a.Name, a.CityId , } into g
select new
{
City = g.Key.Name,
PricePerSqM = g.Key.PricePerSqM,
TotalPrice = g.Sum(x => x.b.Price) + g.Key.PricePerSqM * squareMeter
};
My Models are:
public class Extras
{
public int ExtrasId { get; set; }
[Required]
public string ExtrasName { get; set; }
public ICollection<CityExtras> CityExtras { get; set; }
}
public class City
{
public int CityId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int PricePerSqM { get; set; }
public ICollection<CityExtras> CityExtras { get; set; }
}
public class CityExtras
{
public int CityId { get; set; }
public City City { get; set; }
public Extras Extras { get; set; }
public int ExtrasId { get; set; }
public int Price { get; set; }
}
I need ExtrasNames and ExtrasId in the query
As they stand, your models are not going to allow you to do this easily. You should add navigation properties to your models, then your Linq will be much cleaner (no need for the double select), and you will be able to navigate upwards to the Extra object and get the data you want.

How to get data from child to parent entity framework core?

I have two table like this -
public class Job
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime AddedTime { get; set; } = DateTime.Now;
public DateTime LastEdit { get; set; } = DateTime.Now;
public string Explanation { get; set; }
public string PhotoString { get; set; }
public bool isActive { get; set; } = true;
public int CompanyId { get; set; }
public Company Company { get; set; }
}
and company -
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Explanation { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string PhotoString { get; set; }
public bool isActive { get; set; } = true;
public int AppUserId { get; set; }
public AppUser AppUser { get; set; }
public List<Job> Jobs { get; set; }
}
I only want to get AppUserId from Company and all Jobs from every Company. I tried this and it gave me error.
using var context = new SocialWorldDbContext();
return await context.Jobs.Where(I => I.isActive == true && I.Company.isActive).Include(I=>I.Company.AppUserId).ToListAsync();
So my question is there any way I can get this data from parent?
Include adds whole entities to the output. To add just one property use Select, something like
context.Jobs
.Where(I => I.isActive == true && I.Company.isActive)
.Select(e => new {Job=e, CompanyAppUserId = e.Company.AppUserId})
.ToListAsync();

Calculate Account Receivables using LINQ

How to calculate account receivable using LINQ.
I have tried this but stuck here.
I have done this in SQL but I want this in LINQ so I can use it in my MVC project.
var sale = saleslist.GroupBy(s => s.BuyerId).Select(s => s.Sum(u => u.Amount)).ToList();
var receipt = receiptslist.GroupBy(r => r.StakeHolderId).Select(t => t.Sum(u => u.Amount)).ToList();
List<AccountReceivablesVM> res = db.StakeHolders
.Where(r=>r.StakeHolderTypeId == "0b85a69e-55f2-4142-a49d-98e22aa7ca10")
.Select(rvm => new AccountReceivablesVM
{
CompanyName = rvm.CompanyName,
Receivables = //don't know what to do here
}).ToList();
Models:
public class StakeHolder
{
public string StakeHolderId { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
public string Contact { get; set; }
public string StakeHolderTypeId { get; set; }
}
public class Sale
{
public string SaleId { get; set; }
public string RefNo { get; set; }
public DateTime Date { get; set; }
public string BuyerId { get; set; }
public string Description { get; set; }
public Nullable<double> Amount { get; set; }
}
public class PaymentsAndReceipt
{
public string PaymentAndReceiptId { get; set; }
public Nullable<int> VoucherNo { get; set; }
public DateTime Date { get; set; }
public string StakeHolderId { get; set; }
public string Description { get; set; }
public Nullable<double> Amount { get; set; }
}
public class AccountReceivablesVM
{
public string CompanyName { get; set; }
public Nullable<double> Receivables { get; set; }
}
Expected Result:
You can join first with stakeholderId and then sum the amount and then group by with company name and stakeholder id, however I write the code in Linq. I have considered the stakeholderid as the primary key of your table just because you have not mentioned the schema of stakeholder so.
var result = from s in db.StakeHolders
join pr in db.PaymentsAndReceipt on s.StakeHolderId equals pr.StakeHolderId
where StakeHolderTypeId == "0b85a69e-55f2-4142-a49d-98e22aa7ca10"
group s by new { s.StakeHolderId,s.CompanyName} into p
select new
{
StakeHolderId= p.Key.StakeHolderId,
CompanyName= p.Key.CompanyName,
Receivables = string.Format("{0:C}", p.Sum(y => y.Amount))
};

LINQ query to get count of joined record

Can somebody help me out writing a LINQ query to get record that are joined? I have two models below. I want to get requirements count that belong to given project and has one or more ProjectTest joined to it.
public class ProjectTest
{
public int ProjectTestID { get; set; }
public int ProjectID { get; set; }
public String Objective { get; set; }
public String Category { get; set; }
public String SubCategory { get; set; }
public String Tags { get; set; }
public virtual ICollection<ProjectRequirement> ProjectRequirements { get; set; }
public virtual ICollection<ProjectTestStep> ProjectTestSteps { get; set; }
}
public class ProjectRequirement
{
public int ProjectRequirementID { get; set; }
public int ProjectID { get; set; }
[Display(Name = "Req No.")]
public String ProjectRequirementIDStr { get; set; }
[Display(Name = "Module")]
public String ModuleName { get; set; }
[Display(Name = "Description")]
public String Description { get; set; }
public virtual ICollection<ProjectTest> ProjectTests { get; set; }
}
I just tried to write it as follows but does not seem working.
db.ProjectRequirements
.Where(e => e.ProjectID == activeProjectID &&
e.ProjectTests
.Select(ept => ept.ProjectTestID)
.Count() > 0)
.Select(e => e.ProjectRequirementID)
.Count();
Currently you are counting the number of ProjectRequirement objects that have a given id and that have at least 1 ProjectTest.
If you want to count the amount of ProjectTests you have for a given ProjectId:
var number = db.ProjectRequirements.Where(e => e.ProjectID == activeProjectID)
.Sum(e => e.ProjectTests.Count());

MVC How to count records in related Models?

I have two models, First is Relations, which is opened with Date, second model is Reservations, now i need to count record in reservations which have choiced Date of Relations. The tables is in Relationship relID from first i record in second table in DatumRID.
How to count records in Reservations which is related by ID to Relations
Model Relations:
public tbl_relacii()
{
tbl_rezervacii = new HashSet<tbl_rezervacii>();
}
[Key]
public int relID { get; set; }
[Column(TypeName = "date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DatumR { get; set; }
public int sedista { get; set; }
public string vozilo { get; set; }
[StringLength(50)]
public string shofer1 { get; set; }
[StringLength(50)]
public string shofer2 { get; set; }
public string noteR { get; set; }
public virtual ICollection<tbl_rezervacii> tbl_rezervacii { get; set; }
public string DatumForDisplay
{
get
{
return DatumR.ToString("d");
}
}
Model Reservations:
public partial class tbl_rezervacii
{
[Key]
public int rID { get; set; }
public int AgentID { get; set; }
[StringLength(10)]
public string karta_br { get; set; }
public int DatumRID { get; set; }
public int patnikID { get; set; }
public int stanicaOD { get; set; }
public int stanicaDO { get; set; }
public decimal cena { get; set; }
public bool povratna { get; set; }
public DateTime? DatumP { get; set; }
public string noteP { get; set; }
public virtual tbl_agenti tbl_agenti { get; set; }
public virtual tbl_patnici tbl_patnici { get; set; }
public virtual tbl_relacii tbl_relacii { get; set; }
public virtual tbl_stanici tbl_stanici { get; set; }
public virtual tbl_stanici tbl_stanici1 { get; set; }
public string relacija
{
get
{
return tbl_stanici.stanica + "=>" + tbl_stanici1.stanica;
}
}
public string relacijaP
{
get
{
return tbl_stanici.stanica + "=>" + tbl_stanici1.stanica + "=>" + tbl_stanici.stanica;
}
}
}
And here is Controller for Relations Index:
public ActionResult Index()
{
return View(db.tbl_relacii.ToList().OrderByDescending(x => x.DatumR));
}
How to count records in Reservations then put Number of records to index of Relations?
I solved simply. In relations model i added just this:
public int Count
{
get
{
return tbl_rezervacii.Count;
}
}
And problem is Solved. Thank you
I think you can achieve using LINQ query. Please find the sample below.
var q = from d in Model.Reservations
select new Relations
{
Count = d.Reservations.Count()
};

Categories

Resources