I am relatively new to .net. I have a situation where I have a class
public class Product
{
public string sku { get; set; }
public string ean { get; set; }
public string price { get; set; }
public string description { get; set; }
public string long_description { get; set; }
public string img_url { get; set; }
public Size size { get; set; }
public Style style { get; set; }
public Brand brand { get; set; }
public Color color { get; set; }
public Category category { get; set; }
public List<Attributes> attributes { get; set; }
}
public class Attributes
{
public List<Attribute> attribute { get; set; }
}
public class Attribute
{
public string name { get; set; }
public string value { get; set; }
}
now my question is I want to add values to List.But facing some problem in adding values to attribute.
I have tried the following,
List<Product> products = new List<Product>();
products = (from inventory in inventoryDetails.AsEnumerable()
select new Product
{
ean = !string.IsNullOrEmpty(inventory.ean) ? inventory.ean : null,
sku = !string.IsNullOrEmpty(inventory.sku) ? inventory.sku : null,
}).ToList();
How to add attribute values? Can anyone please help?
You have multiple ways to write this
without lambda expression
List<Product> products = (from inventory in inventoryDetails.AsEnumerable()
select new Product
{
ean = !string.IsNullOrEmpty(inventory.ean) ? inventory.ean : null,
sku = !string.IsNullOrEmpty(inventory.sku) ? inventory.sku : null,
attributes = inventory.attributes.Select(x => new Attributes
{
//Set properties
}).ToList()
}).ToList();
With Lambda Expression
List<Product> products = inventoryDetails.Select(inventory => new Product
{
ean = !string.IsNullOrEmpty(inventory.ean) ? inventory.ean : null,
sku = !string.IsNullOrEmpty(inventory.sku) ? inventory.sku : null,
attributes = inventory.attributes
// if you want to set properties uncomment below lines and comment above line
//attributes = inventory.attributes.Select(y => new Attributes
//{
////Set properties
//}).ToList()
}).ToList();
You didn't share about inventoryDetails but you could apply select for also attributes;
products = (from inventory in inventoryDetails.AsEnumerable()
select new Product
{
ean = !string.IsNullOrEmpty(inventory.ean) ? inventory.ean : null,
sku = !string.IsNullOrEmpty(inventory.sku) ? inventory.sku : null,
attributes = inventory.attributes.Select(x => new Attributes
{
//Set properties
})
}).ToList();
When a model class cantains a List or collection fields we must intiate them at class constructor like this
public class Product
{
public Product()
{
this.attributes = new List<Attributes>();
}
public string sku { get; set; }
public string ean { get; set; }
public string price { get; set; }
public string description { get; set; }
public string long_description { get; set; }
public string img_url { get; set; }
public Size size { get; set; }
public Style style { get; set; }
public Brand brand { get; set; }
public Color color { get; set; }
public Category category { get; set; }
public List<Attributes> attributes { get; set; }
}
If any case Attribues model is mapped to database then use Icollection instead of List
public Product()
{
this.attributes = new ICollection<Attributes>();
}
Related
So this is my entity:
public class Stock {
public Guid ID { get; set; }
public decimal Qty { get; set; }
.....
}
I have a lot of inheritance to this Stock:
public class StockA : Stock {
public string Spec { get; set; }
....
}
public class StockB : Stock {
public string Color { get; set; }
....
}
public class StockC : Stock {
public string Variant { get; set; }
....
}
public class StockD : Stock {
public string Type { get; set; }
....
}
.....
Let us say there are more than 10 inheritances. How can I get all columns from Stock and its inheritances?
For example I need these columns:
ID
Qty
Spec
Color
Variant
Type
....
I tried to define a combined entity:
public class AllStock {
public Guid ID { get; set; }
public decimal Qty { get; set; }
public string Spec { get; set; }
public string Color { get; set; }
public string Variant { get; set; }
public string Type { get; set; }
.....
}
I set it in my DBContext:
public DbSet<AllStock> AllStocks { get; set; }
But when I query it:
var x = await db.AllStocks.ToList();
It returns empty list. I suppose this AllStock entity is separated from the other entity.
How can I do it?
Try the following Select:
var result = await db.Stocks
.Select(x => new
{
x.ID,
x.Qty,
Spec = x is StockA ? ((StockA)x).Spec : null,
Color = x is StockB ? ((StockB)x).Color : null,
Variant = x is StockC ? ((StockC)x).Variant : null,
Type = x is StockD ? ((StockD)x).Type : null
})
.ToListAsync();
I am able to do this with FromSqlRaw.
First assign the DbSet:
public DbSet<StockVM> AllStocks { get; set; }
then set the model builder with HasNoKey:
mb.Entity<StockVM>().HasNoKey();
then this is the query:
return db.AllStocks.FromSqlRaw(#"
SELECT" +
GetSelect() +
#" FROM Stocks
INNER JOIN Colors ON Stocks.ColorId = Colors.ID
INNER JOIN Units ON Stocks.UnitId = Units.ID
INNER JOIN Items ON Stocks.ItemId = Items.ID
INNER JOIN ItemTypes ON Stocks.ItemTypeId = ItemTypes.ID
");
Also I have to create an entity with all of the properties:
public class StockVM{
public Guid ID { get; set; }
public decimal Qty { get; set; }
public string Spec { get; set; }
public string Color { get; set; }
public string Variant { get; set; }
public string Type { get; set; }
.....
}
IMPORTANT
Be careful with the migration, make sure you delete the AllStock from the Up(). Or it will try to create a new column.
I'm getting data from an Oracle database and creating an API for internal use. Some of the classes are (shortened for brevity):
CustomerOrderTab
Public partial class CustomerOrderTab
Public string OrderNo { get; set; }
[ForeignKey("CustomerMV")]
public string CustomerNo { get; set; }
public List<CustomerOrderLineTab> CustomerOrderLines { get; set; }
public List<CustomerOrderChargeTab> CustomerOrderCharge { get; set; }
public List<ShipmentOrderLineTab> ShipmentOrderLines { get; set; }
public CustomerMV CustomerMV { get; set; }
CustomerOrderDTO
Public class OrderDTO
public string OrderNo { get; set; }
public string CustomerName { get; set; }
public List<OrderLinesDTO> OrderLines { get; set; }
public List<OrderChargesDTO> OrderCharges { get; set; }
public List<ShipmentOrderLinesDTO> ShipmentOrderLines { get; set; }
ShipmentOrderLineTab
public partial class ShipmentOrderLineTab
public decimal ShipmentId { get; set; }
[ForeignKey("CustomerOrderTab")]
public string OrderNo { get; set; }
public ShipmentTab Shipment { get; set; }
ShipmentOrderLineDTO
public class ShipmentOrderLinesDTO
public decimal ShipmentId { get; set; }
public string OrderNo { get; set; }
public ShipmentTab MyShipment { get; set; }
ShipmentTab
public partial class ShipmentTab
[ForeignKey("ShipmentOrderLineTab")]
public decimal ShipmentId { get; set; }
public string ShipperAddress1 { get; set; }
public string ShipperAddress2 { get; set; }
public List<ShipmentHandlingUnitTab> ShipmentHandlingUnits { get; set; }
ShipmentDTO
public class ShipmentDTO
public decimal ShipmentId { get; set; }
public string ShipViaCode { get; set; }
public string ShipmentPayer { get; set; }
public List<ShipmentHandlingUnitDTO> ShipmentHandlingUnitDTOs { get; set; }
This Works:
var orderLines = from o in _context.CustomerOrderTab
.Where(o => o.OrderNo == orderno)
select new OrderDTO()
{
OrderNo = o.OrderNo,
CustomerName = o.CustomerMV.CustomerName,
This is a child of the order ShipmentOrderLines = o.ShipmentOrderLines
This works .Select(ob => new ShipmentOrderLinesDTO
{
ShipmentId = ob.ShipmentId,
OrderNo = ob.OrderNo,
MyShipment = ob.Shipment
Adding this does not work .Select(y => new ShipmentDTO
The error says that ShipmentTab
Doesn’t have a definition for Select {
}
}).ToList()
Shipment is a child of ShipmentOrderLine (there will only be one shipment per line)
ShipmentOrderLine is a child of CustomerOrder (there can be many lines per order)
I think the problem is that there is only one shipment per line but I've tried lots of things and can't get it to map to my DTO.
Fix your model:
ShipmentOrderLineDTO
public class ShipmentOrderLinesDTO
public decimal ShipmentId { get; set; }
public string OrderNo { get; set; }
public ShipmentDTO MyShipment { get; set; }
Select is only used to project a collection. For non-collections, you just create a new object...
var orderLines = _context.CustomerOrderTab
.Where(o => o.OrderNo == orderno)
.Select(o => new OrderDTO {
OrderNo = o.OrderNo,
CustomerName = o.CustomerMV.CustomerName,
ShipmentOrderLines = o.ShipmentOrderLines
.Select(ob => new ShipmentOrderLinesDTO {
ShipmentId = ob.ShipmentId,
OrderNo = ob.OrderNo,
MyShipment = new ShipmentDTO {
ShipmentId = ob.Shipment.ShipmentId,
...
ShipmentHandlingUnits = ob.Shipment.ShipmentHandlingUnits
.Select(shu=> new ShipmentHandlingUnitDTO {
...
}).ToList()
}
}
}).ToList()
Now with that all said, I typically have mapping extension methods on my data model classes, which allow things like this:
var orderLines = _context.CustomerOrderTab
.Where(o=>o.OrderNo == orderno)
.Select(o=> o.ToDto());
Example class:
public static class CustomerOrderTabExtensions {
public static CustomerOrderDto ToDto(this CustomerOrderTab cot) {
return new CustomerOrderDto {
OrderNo = cot.OrderNo,
...
OrderLines = cot.CustomerOrderLines
.Select(col=>col.ToDto())
.ToList()
}
}
}
Or use Automapper.
I am trying to populate the AllTerms object that will contain LegalFundClassCommercialViewModel and LegalFundClassSideLetterViewModel objects.
Basically the LEGAL_FUND_CLASS table has parent and child records and are related by column LegalParentClassId. One parent has one child. So I need to loop through legalfundClasses object and populate
IEnumerable<LegalFundClassWrapper> AllTerms . The LegalFundClassDetailsViewModel represents the records in the LEGAL_FUND_CLASS table. So legalfundClasses variable contains records from this legal_fund_class table. There are several records. Some records wont have child record. I need to populate in a way where the parent record gets added to LegalFundClassCommercialViewModel and its child record gets added to
LegalFundClassSideLetterViewModel. The wrapper would contain a collection of Parent and child records where some child records wont exist and hence the LegalFundClassSideLetterViewModel property would be null.
Can somebody give me an idea on how to go about it ?
C#
public class LegalFundClassViewModel
{
public IEnumerable<LegalFundClassWrapper> AllTerms;
public class LegalFundClassWrapper
{
public LegalFundClassDetailsViewModel LegalFundClassCommercialViewModel { get; set; }
public LegalFundClassDetailsViewModel LegalFundClassSideLetterViewModel { get; set; }
}
}
public class LegalFundClassDetailsViewModel
{
public string Description { get; set; }
public string AuditSummary { get; set; }
public string FeesReviewSummary { get; set; }
public string TermsReviewSummary { get; set; }
public int Id { get; set; }
public int FundId { get; set; }
public int FundClassType { get; set; }
public int? CurrencyId { get; set; }
public string PrimaryCurrencyName { get; set; }
public string OtherCurrencyName { get; set; }
public int? ManagerStrategyId { get; set; }
public string ManagerStrategyName { get; set; }
public int? SubVotingId { get; set; }
public string SubVotingName { get; set; }
public int? SubHotIssueId { get; set; }
public string SubHotIssueName { get; set; }
public int? RedsFrqncyId { get; set; }
public string RedsFrqncyName { get; set; }
public int? RedsNoticeDays { get; set; }
public int? NoticeTypeOfDaysId { get; set; }
public string NoticeTypeOfDaysName { get; set; }
public int? LegalParentClassId { get; set; }
}
var managerStrategyFundIds = GetService<MANAGERSTRATEGY>().WhereWithIncludes<MANAGERSTRATEGY>(x => x.ID == managerStratedyId, x => x.FUNDs).SelectMany(x => x.FUNDs).Select(x => x.ID).ToList();
var legalfundClasses = GetService<LEGAL_FUND_CLASS>().Where(x => managerStrategyFundIds.Contains(x.FUND_ID));
What I was trying creates a list of all the records in one. How do I loop through and populate the AllTerms
var allFunds = legalfundClasses.Select(fc => new LegalFundClassDetailsViewModel
{
Description = fc.DESCRIPTION,
Id = fc.ID,
FundId = fc.FUND_ID,
FundClassType = fc.CLASS_TYPE,
AuditSummary = getAuditSummary(managerStratedyId, fc.ID),
FeesReviewSummary = getFeesReviewSummary(fc),
TermsReviewSummary = getTermsReviewSummary(fc),
CurrencyId = fc.CURRENCY_ID,
});
public class LegalFundClassViewModel
{
public IEnumerable<LegalFundClassWrapper> AllTerms;
public class LegalFundClassWrapper
{
public LegalFundClassDetailsViewModel
LegalFundClassCommercialViewModel { get; set; }
public LegalFundClassDetailsViewModel
LegalFundClassSideLetterViewModel { get; set; }
}
As you can see in the image below, there are two records. The record that has value in legal_parent_class id field is the child to the record on top of it. If you notice the id of the top record matches the bottom record's legal_parent_class_id.
What is the best way to identify the child and store records in respective properties accordingly
You need left outer join. In your case
var allFunds = new[]
{
new LegalFundClassDetailsViewModel
{
Id = 101,
Description = "Parent with child"
},
new LegalFundClassDetailsViewModel
{
Id = 102,
Description = "Parent without child"
},
new LegalFundClassDetailsViewModel
{
Id = 103,
Description = "I'm child",
LegalParentClassId = 101
}
};
var allTerms = (from fund in allFunds
where fund.LegalParentClassId == null //only parents
join child in allFunds on fund.Id equals child.LegalParentClassId into gj
from child2 in gj.DefaultIfEmpty()
select new LegalFundClassViewModel.LegalFundClassWrapper { LegalFundClassCommercialViewModel = fund, LegalFundClassSideLetterViewModel = child2 })
.ToArray();
I have a Model:
public class Transaction
{
public Guid ID { get; set; }
public Guid CategoryID { get; set; }
public List<Guid> Tags { get; set; }
}
public class Category
{
public Guid ID { get; set; }
public string Caption { get; set; }
}
public class Tag
{
public Guid ID { get; set; }
public string Caption { get; set; }
}
I have a ModelRepository of Model objects. I have VieModels:
public class TransactionViewModel
{
public Guid ID { get; set; }
public CategoryViewModel Category { get; set; }
public List<TagViewModel> Tags { get; set; }
}
public class CategoryViewModel
{
public Guid ID { get; set; }
public string Caption { get; set; }
}
public class TagViewModel
{
public Guid ID { get; set; }
public string Caption { get; set; }
}
Now I need to make List<TransactionViewModel> from List <Transaction> using linq. How did I:
VM.Categories = ModelRepository.Categories.Select(p => new CategoryViewModel(p)));
VM.Tags = ModelRepository.Tags.Select(p => new TagViewModel(p)));
var trans = from t in ModelRepository.Transactions
join c in VM.Categories on t.CategoryID equals c.ID
select new TransactionViewModel()
{
...,
Category = c
};
VM.Transactions = trans.ToList();
Now when I change any CategoryViewModel in VM.Categories, I immediately get changes for all TransactionViewModel.Category in VM.Transactions. Question - how do I fill TransactionViewModel.Tags? Preferably with LINQ. And it's mandatory that when changing any TagViewModel in VM.Tags, I immediately get changes for all TransactionViewModel.Tags in VM.Transactions.
Below is the Entity class
public partial class TestPlanViewModel
{
public TestPlanViewModel()
{
this.TestPlanTestPoints = new List<TestPlanTestPoint>();
}
public int TestPlanId { get; set; }
public string TestPlanName { get; set; }
public virtual IList<TestPlanTestPoint> TestPlanTestPoints { get; set; }
}
public class TestPlanTestPoint
{
public int OrganizationId { get; set; }
public int TestPlanId { get; set; }
public string TestPlanName { get; set; }
public int TestPlanVersion { get; set; }
public int TestPointId { get; set; }
public string TestPointName { get; set; }
}
I need to write a query where I need to get the collections from the dbContext like,
var query = (from tpm in TestPlanMaster
join tptp in TestPlanTestPoint on tpm.TestPlanId equals tptp.TestPlanId
join tmm in TestMethodMaster on tptp.TestMethodId equals tmm.TestMethodId
join tpma in TestPointMaster on tptp.TestPointId equals tpma.TestPointId
select new
{
//Plan Details
tpm.TestPlanId,
tpm.TestPlanName,
}).ToList().Select(x => new Entities.CustomEntities.TestPlanViewModel ====> Custom Entity
{
TestPlanId = x.TestPlanId,
TestPlanName = x.TestPlanName,
TestPlanTestPoints = ?????? ==> how to fill this collection
});
As shown above the TestPlanTestPoints is the IList collection object. I need to populate the data with the values from TestPlanTestPoint table.
Any suggestions?
Model
TestPlan
public partial class TestPlanMaster
{
[DataMember]
public int TestPlanId { get; set; }
[DataMember]
public short TestPlanVersion { get; set; }
[DataMember]
public int OrganizationId { get; set; }
[DataMember]
public short TestPlanTypeId { get; set; }
[DataMember]
public string TestPlanName { get; set; }
}
TestPlanTestPointMapping Model
public partial class TestPlanTestPointMapping
{
[DataMember]
public int OrganizationId { get; set; }
[DataMember]
public int TestPlanId { get; set; }
[DataMember]
public short TestPlanVersion { get; set; }
[DataMember]
public int TestPointId { get; set; }
}
You are thinking too much sql, think more linq. You want to select "tpm" items, so just write a select of those and select the new TestPlanViewModel and fill its properties and navigational properties.
I'm assuming you have a TestPlanTestPoints navigational property in your TestPlanMaster.
var q = (from tpm in TestPlanMaster
select new TestPlanViewModel
{
TestPlanId = tpm.TestPlanId,
TestPlanName = tpm.TestPlanName,
TestPlanPoints = TestPlanTestPoint.Where(pr => tpm.TestPlanId == pr.TestPlanId).Select(tptp => new TestPlanTestPoint()
{
// Fill properties here
}
}).ToList();