Linq to Entities subquery to fill array? - c#

New at linq to entities trying to figure this out. I have the following tables:
Customer: Cust_Id, Name
Orders: Order_Id
CustomerOrders: Cust_Id, Order_Id
I have a class like so:
public class Customers
{
public List<Row> Rows { get; set; }
public Customers()
{
Rows = new List<Row>();
}
public class Row
{
public int Key { get; set; }
public string Name { get; set; }
public List<string> Order_Ids { get; set; }
}
}
Linq query is like this:
var query = from c in context.Customer
select new Customers.Row
{
Key = c.Cust_Id,
Name = c.Name,
Order_IDs = List<string>( ?? )
};
foreach (var row in query)
{
Customers.Rows.Add(row);
}
var serializer = new JavaScriptSerializer();
return serializer.Serialize(Customers);
Where I have '??', can I use a subquery or something to get a list of Order_Id's from the CustomerOrders table?
Right Now, I can only think to loop through the Customers table once it is filled and then query the DB again to get each array of Order Id's for each Customer.

If it's not a requirement, drop the "Row" collection from the "Customer" object. This should suffice:
public class Customer
{
public int Key { get; set; }
public string Name { get; set; }
public List<string> Order_Ids { get; set; }
}
Then you can query like this:
var customers = from c in context.Customers
select new Customer
{
Key = c.Cust_Id,
Name = c.Name,
Order_IDs = c.Orders.Select(o => o.Order_Id).ToList()
};
It's better to deal in objects when writing C# and using EF, than to deal in terms of tables and rows -less confusing.

Try something like this:
var query = from c in context.Customer
select new Customers.Row
{
Key = c.Cust_Id,
Name = c.Name,
Order_Ids = c.Rows.Select(row => row.Key.ToString()).ToList()
};
Where you have .Select(row => row.Key.ToString()) you can set the property you need (Key, Name, etc...). Select method is an extension method to IEnumerable and it return a collection of type of property you have seted, in this case, a collection of strings because I converted it with ToString() method.

Related

Comparing two table IDs. ASP.NET MVC

I am currently loading two Orders and Colors tables, I wanted the Colors table to list the items that have the ID equal to Orders. For this, what occurred to me was to assign the IdOrders values ​​to a variable and compare it with my IdOrders (in my table Colors), but it is not possible to assign the database's balance to my variable
My tables:
public partial class Orders
{
public int ID_Orders { get; set; }
public Nullable<System.DateTime> Data_Registo { get; set; }
public string Num_Encomenda { get; set; }
public string Ref_Cliente { get; set; }
}
public partial class Colors
{
public int ID_Orders { get; set; }
public int ID_Programa_Malha { get; set; }
public int ID_Linha_Cor { get; set; }
public string Cor { get; set; }
}
I am working with a database already in operation and possible these tables are already used in a sql join but not how to process that information.
As I said the first thing I remembered was to do this:
My Controller:
var id = from d in db.Orders
select d.ID_Orders;
var color = db.Colors.Where(x => x.ID_Orders = id).ToList();
var tables = new EncomendaViewModel
{
Orders= db.Orders.ToList(),
Colors= color.ToList(),
};
return View(tables);
Error in id: CS0029 C# Cannot implicitly convert type to 'int'
Is it possible to process the data in this way?
Thanks for anyone who can help!
-------------------(Update)------------------------------------------------
Using == cs0019 operator '==' cannot be applied to operands of type
My view in Broswer
dbEntities sd = new dbEntities();
List<Orders> orders= sd.Orders.ToList();
List<Colors> colers= sd.Colors.ToList();
var multipletable = from c in orders
join st in colers on c.ID_Programa equals st.ID_Programa into table1
from st in table1.DefaultIfEmpty()
select new MultipleClass { orders= c, colers= st };
There could be one or more values returned from the below query.
var id = from d in db.Orders
select d.ID_Orders;
That is the reason why it was throwing an error.
So lets try it this way
var color = db.Colors.Where(x => id.Contains(x.ID_Orders)).ToList();
public class OrderWithColorsViewModel
{
public Order order { get; set; }
public List<Colors> colers{ get; set; }
}
Public class TestOrderController : Controller
{
public DailyMVCDemoContext db = new DailyMVCDemoContext();
public ActionResult Index()
{
var orders= db.Orders.ToList();
var colers = db.Colors.ToList();
var result = (from c in orders
join st in colers on c.ID_Orders equals st.id into table1
select new OrderWithColorsViewModel { order =c, colers =
table1.ToList() }).ToList();
return View(result);
}
}
credits: YihuiSun

LINQ create generic List of nestet objects

How can I get a List<Type1> which includes another List<Type2> from another List<Type3>?
Here is the situation:
I have a List<DbStruncture>. Each entry includes a DatabaseStructure
public partial class DatabaseStructure
{
public string TableSchema { get; set; }
public string TableName { get; set; }
public string ColumnName { get; set; }
public bool? IsPrimaryKey { get; set; }
}
I also have
public class Table
{
public string Name { get; set; }
public string Schema { get; set; }
public List<Column> Columns { get; set; }
}
public class Column
{
public string Name { get; set; }
public bool? IsPrimaryKey { get; set; }
}
Now I want to fill the Data from the List<DatabaseStructure> into a List<Table> which includes a List<Column> with all the Columns of that Table.
I tried it with LINQ and this is how far I got:
var query =
from t in result
group t.TableName by t.TableName
into tn
select new
{
Table = tn.Key,
Schema = from s in result where s.TableName == tn.Key select s.TableSchema.First(),
Columns = from c in result where c.TableName == tn.Key select new Column
{
Name = c.ColumnName,
IsPrimaryKey = c.IsPrimaryKey
}
};
The problem with my solution is, that my query is not a generic List...
Can anybody point me into the right direction? Is LINW the right way here? If yes, how do I get the wanted result?
Thanks in advance
Preface: I prefer (and recommend) using Linq with the Extension Method syntax instead of using the from,group,into keywords because it's more expressive and if you need to do more advanced Linq operations you'll need to use Extension Methods anyway.
To begin with, your input is denormalized (I presume the output of running SELECT ... FROM INFORMATION_SCHEMA.COLUMNS) where each row contains repeated table information, so use GroupBy to group the rows together by their table identifier (don't forget to use both the Table Schema and Table Name to uniquely identify a table!)
Then convert each group (IGrouping<TKey: (TableSchema,TableName), TElement: DatabaseStructure>) into a Table object.
Then populate the Table.Columns list by performing an inner Select from the IGrouping group and then .ToList() to get a concrete List<Column> object.
My expression:
List<DatabaseStructure> input = ...
List<Table> tables = input
.GroupBy( dbs => new { dbs.TableSchema, dbs.TableName } )
.Select( grp => new Table()
{
Name = grp.Key.TableName,
Schema = grp.Key.TableSchema,
Columns = grp
.Select( col => new Column()
{
Name = col.Name,
IsPrimaryKey = col.IsPrimaryKey
} )
.ToList()
} )
.ToList()
OK, just found the answer myself.
Here it is:
var query =
(from t in result
group t.TableName by t.TableName
into tn
select new Table
{
Name = tn.Key,
Schema = (from s in result where s.TableName == tn.Key select s.TableSchema).First(),
Columns = (from c in result
where c.TableName == tn.Key
select new Column
{
Name = c.ColumnName,
IsPrimaryKey = c.IsPrimaryKey
}).ToList()
});

Select categories with subcategories [duplicate]

I have the following entity:
public class Item
{
public int Id { get; set; }
public int? ParentId { get; set; }
public Item Parent { get; set; }
public List<Item> Children { get; set; }
public double PropertyA { get; set; }
public double PropertyB { get; set; }
...
}
Now I want to query the database and retrieve data of all the nested children.
I could achieve this by using Eager Loading with Include():
var allItems = dbContext.Items
.Include(x => Children)
.ToList();
But instead of Eager Loading, I want to do the following projection:
public class Projection
{
public int Id { get; set; }
public List<Projection> Children { get; set; }
public double PropertyA { get; set; }
}
Is it possible to retrieve only the desired data with a single select?
We are using Entity Framework 6.1.3.
Edit:
This is what I have tried so far.
I really don't know how to tell EF to map all child Projection the same way than their parents.
An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll
Additional information: The type 'Projection' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.
var allItems = dbContext.Items
.Select(x => new Projection
{
Id = x.Id,
PropertyA = x.PropertyA,
Children = x.Children.Select(c => new Projection()
{
Id = c.Id,
PropertyA = c.PropertyA,
Children = ???
})
})
.ToList();
Generally speaking, you can't load a recursive structure of unknown unlimited depth in a single SQL query, unless you bulk-load all potentially relevant data irregardless whether they belong to the requested structure.
So if you just want to limit the loaded columns (exclude PropertyB) but its ok to load all rows, the result could look something like the following:
var parentGroups = dbContext.Items.ToLookup(x => x.ParentId, x => new Projection
{
Id = x.Id,
PropertyA = x.PropertyA
});
// fix up children
foreach (var item in parentGroups.SelectMany(x => x))
{
item.Children = parentGroups[item.Id].ToList();
}
If you want to limit the number of loaded rows, you have to accept multiple db queries in order to load child entries. Loading a single child collection could look like this for example
entry.Children = dbContext.Items
.Where(x => x.ParentId == entry.Id)
.Select(... /* projection*/)
.ToList()
I see only a way with first mapping to anonymous type, like this:
var allItems = dbContext.Items
.Select(x => new {
Id = x.Id,
PropertyA = x.PropertyA,
Children = x.Children.Select(c => new {
Id = c.Id,
PropertyA = c.PropertyA,
})
})
.AsEnumerable()
.Select(x => new Projection() {
Id = x.Id,
PropertyA = x.PropertyA,
Children = x.Children.Select(c => new Projection {
Id = c.Id,
PropertyA = c.PropertyA
}).ToList()
}).ToList();
A bit more code but will get the desired result (in one database query).
Let's say we have the following self-referencing table:
public class Person
{
public Person()
{
Childern= new HashSet<Person>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? ParentId { get; set; }
[StringLength(50)]
public string Name{ get; set; }
public virtual Person Parent { get; set; }
public virtual ICollection<Person> Children { get; set; }
}
And for some point of time you need to get all grandsons for specific persons.
So, first of all I will create stored procedure(using code-first migration) to get all persons in the hierarchy for those specific persons:
public override void Up()
{
Sql(#"CREATE TYPE IdsList AS TABLE
(
Id Int
)
GO
Create Procedure getChildIds(
#IdsList dbo.IdsList ReadOnly
)
As
Begin
WITH RecursiveCTE AS
(
SELECT Id
FROM dbo.Persons
WHERE ParentId in (Select * from #IdsList)
UNION ALL
SELECT t.Id
FROM dbo.Persons t
INNER JOIN RecursiveCTE cte ON t.ParentId = cte.Id
)
SELECT Id From RecursiveCTE
End");
}
public override void Down()
{
Sql(#" Drop Procedure getChildIds
Go
Drop Type IdsList
");
}
After that you can use Entity Framework to load the ids(you could modify stored procedure to return persons instead of only returning ids) of persons under the passed persons(ex grandfather) :
var dataTable = new DataTable();
dataTable.TableName = "idsList";
dataTable.Columns.Add("Id", typeof(int));
//here you add the ids of root persons you would like to get all persons under them
dataTable.Rows.Add(1);
dataTable.Rows.Add(2);
//here we are creating the input parameter(which is array of ids)
SqlParameter idsList = new SqlParameter("idsList", SqlDbType.Structured);
idsList.TypeName = dataTable.TableName;
idsList.Value = dataTable;
//executing stored procedure
var ids= dbContext.Database.SqlQuery<int>("exec getChildIds #idsList", idsList).ToList();
I hope my answer will help others to load hierarchical data for specific entities using entity framework.

Mapping Linq Group By Results To An Object

I have a class that acts as a summary which is going to be passed to an MVC View as an IEnumerable. The class looks like:
public class FixedLineSummary
{
public long? CustomerId { get; set; }
public string CustomerName { get; set; }
public int? NumberOfLines { get; set; }
public string SiteName { get; set; }
}
The results returned from the db have all of the single entries and so I use linq to summarise these using:
var summary = (from r in result
let k = new {r.CustomerId, CustomerName = r.CompanyName, r.SiteName}
group r by k into t
select new
{
t.Key.CustomerId,
t.Key.CustomerName,
t.Key.SiteName,
Lines = t.Sum(r => r.lines)
});
When I try and cast the results into my object however I just keep getting an error that:
Instance argument: cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<Domain.Entities.FixedLineSummary>'
Is there a way to cast the results of the linq query into an enumerable of my class?
You should change the projection to create your class, rather than an anonymous type:
var summary = from r in result
let k = new {r.CustomerId, CustomerName = r.CompanyName, r.SiteName}
group r by k into t
select new FixedLineSummary
{
CustomerId = t.Key.CustomerId,
CustomerName = t.Key.CustomerName,
SiteName = t.Key.SiteName,
NumberOfLines = t.Sum(r => r.lines)
};
You cannot cast the anonymous type to FixedLineSummary since both are not related at all(for the compiler). Instead you need to create instances of your class manually:
IEnumerable<FixedLineSummary> summaries = summary
.Select(s => new FixedLineSummary
{
CustomerId = s.CustomerId,
CustomerName = s.CustomerName,
NumberOfLines = s.NumberOfLines,
SiteName = s.SiteName
})
.ToList();

searching a List<>

I have a List<Order>
public int OrderID { get; set; }
public string CustID { get; set; }
public string Details { get; set; }
I want to write a method that accepts a ID, then searches this List for matching records that have same CustID and returns ORderID and Details in a List<>
This will get a sequence of Order objects that match the criteria:
var ordersIWant = myList.Where(order => order.CustID == "some customer ID");
public List<Order> Get(string id)
{
List<Order> orders = new List<Order>(); // pass this in as a param or globally refer to it
var query = from o in orders
where o.CustID == id
select o;
return query.ToList();
}
Or if you want to specifically return only those two fields maybe something like:
public class Order : IOrderDetails
{
public int OrderID { get; set; }
public string CustID { get; set; }
public string Details { get; set; }
}
public interface IOrderDetails
{
int OrderID { get; set; }
string Details { get; set; }
}
public List<IOrderDetails> Get(string id)
{
List<Order> orders = new List<Order>(); // pass this in as a param or globally refer to it
var query = from o in orders
where o.CustID == id
select o as IOrderDetails;
return query.ToList();
}
Assuming those properties you listed belong to a class.
string searchId="15";
var list = (from item in myList
where item.OrderId == searchId
select new {OrderId= item.OrderId,Details = item.Details }).ToList();
Just wrote that without compiling... good luck.
Since you only wanted OrderID and Details I returned an anonymous object. Could also just return item.

Categories

Resources