How to get entity collection from context in code dynamically? - silverlight-4.0

Suppose I have 2 tables : tab1, tab2, with EF and Wcf Ria service, there are 2 entity Tab1, Tab2 available at client side of domaincontext.
Then I want to get the entityset dynamically in code, like
MyDomainContext.Entities("Tab1");
How can I do this?

In your client side code you will have a reference, such as:
using System.ServiceModel.DomainServices.Client;
Then you would load collections of your entities like so:
var ctx = new MyDomainContext();
ctx.Load<tab1>( _ctx.GetTab1Query(), LoadBehavior.RefreshCurrent, (op) =>
{
var data = op.Entities;
} , null );
In the above code snippet your server side domain service has provided you with the GetTab1Query.

I've seen this in Kyle McClellan's code in his ComboBoxDataSource. He takes a string parameter and calls an Operation (or Query). This is now part of the RiaServicesContrib project in the ComboBoxDataSource module.
The essentials (from ComboBoxDataSource.cs, Refresh method):
Type domainContextType = this.DomainContext.GetType();
MethodInfo operationInfo = domainContextType.GetMethods().Where(
m => (m.Name == this.OperationName) && (m.GetParameters().Count() == this.Parameters.Count)).FirstOrDefault();
this.Operation = (InvokeOperation)operationInfo.Invoke(this.DomainContext, this.Parameters.Select(p => p.Value).ToArray());
this.Operation.Completed += this.OnInvokeCompleted;

Related

EF CORE Power Tools DbContextExtensions ambiguity

I use the EF CORE Power Tool to generate database classes in two separate .Net class library projects. A third WebAPI project references these libraries. The compilation succeeds when only one stored procedure is included in one of the libraries. I get following error when a second stored procedure is included in the other library. I think there are two identical DbContextExtensions that cause this problem. How to solve this ambiguity? Thanks.
The call is ambiguous between the following methods or properties: 'IPRehabModel.DbContextExtensions.SqlQueryAsync
(Microsoft.EntityFrameworkCore.DbContext, string, object[], System.Threading.CancellationToken)' and 'UserModel.DbContextExtensions.SqlQueryAsync
(Microsoft.EntityFrameworkCore.DbContext, string, object[], System.Threading.CancellationToken)' IPRehabWebAPI2 C:\Users\xxx\yyy\repos\theApp\IPRehabWebAPI2\Helpers\UserPatientCacheHelper.cs 58 Active
Here is the code for that contains the error
public async Task <List<MastUserDTO>> GetUserAccessLevels(string networkID) {
string userName = CleanUserName(networkID); //use network ID without domain
SqlParameter[] paramNetworkID = new SqlParameter[] {
new SqlParameter() {
ParameterName = "#UserName",
SqlDbType = System.Data.SqlDbType.VarChar,
Direction = System.Data.ParameterDirection.Input,
Value = userName
}
};
/*line58*/
var userPermission = await
_context.SqlQueryAsync <theStoredProcedureResult> (
$ "execute [Apps].[theStoredProcName] #UserName", paramNetworkID);
var distinctFacilities = userPermission
.Where(x => !string.IsNullOrEmpty(x.Facility)).Distinct()
.Select(x => HydrateDTO.HydrateUser(x)).ToList();
return distinctFacilities;
}

How to run normally query script in entity framework mvc c#

I have face problem about entity framework in mcv c#,
i decide to change the way to exec query to normally query scripting,
this bellow script I have for exemple
//for only one row result
string activeUser = await db.Users.Where(x => x.Token.Equals(token)).Select(x => x.Username).FirstOrDefaultAsync();
ReceivingSFG receiving = await db.ReceivingSFGs.Where(s => s.ID.Equals(receivingVM.ID)).FirstOrDefaultAsync();
//for multiple row result (List)
IQueryable<ReceivingSFGDetail> query = db.ReceivingSFGDetails.Where(s => s.ReceivingID.Equals(req.ID)).AsQueryable();
IEnumerable<ReceivingSFGDetail> list = Enumerable.Empty<ReceivingSFGDetail>();
list = query.ToList();
IEnumerable<ReceivingSFGDetailDTO> listDto = Enumerable.Empty<ReceivingSFGDetailDTO>();
string message = "";
bool status = false;
listDto = from x in list
select new ReceivingSFGDetailDTO
{
ID = x.ID,
ReceivingID = x.ReceivingID,
Barcode = x.Barcode,
QtyActual = x.QtyActual,
QtyBag = x.QtyBag,
CreatedBy = x.CreatedBy,
CreatedDate = x.CreatedDate,
QtyPerBag = x.QtyPerBag
};
or some case that I never use before,
like how to exec store procedure... please some one can help me to solve this case.
If you want to execute Stored Procedure vie Entity framework you will of course have to start by mapping it into the data context.
Once the stored procedure is mapped in your model layer you can simply call it pseudo like this:
List<SomeStuff_Result> list = _db.NameOfStoredProcedure(string somevariable).ToList();
It should behave the same way any object you receive from data layer.
You can also check this answer.

.NET Core - EntityFrameworkCore - Unable to cast object of type 'Query.Internal.EntityQueryable` to type 'DbSet`

I try to implement a search with entity when a search field is provided
but I get a weird casting error I just dont understand
Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[SomeApp.Models.Partner]' to type 'Microsoft.EntityFrameworkCore.DbSet`1[SomeApp.Models.Partner]'.
here is the code of my controller entry point
I tried forcing the cast, but apparently there is something wrong with my code
[HttpPost]
public async Task<ActionResult<PartnersFetch>> GetPartners(PartnersSearch partnersSearch)
{
DbSet<Partner> data = _context.Partners;
if (partnersSearch.SearchById != null)
{
// the following line causes problems :
data = (DbSet <Partner>) data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
}
thanks for helping me on this
I forgot to use AsQueryable
var data = _context.Partners.AsQueryable();
if (partnersSearch.SearchById != null)
{
data = data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
}
data.Where(...) will return an IQueryable which you can materialize as follows
List<Partner> myResult = data.Where(...).ToList();
The DbSet<Partner> is only the set on which you can query data. Your goal very likely is to get the partners out of it, right?

NHibernate database call count?

Is there a way to get at runtime the number of calls NHibernate is making to the database?
I know I can use the NHibernate profiler (NHProf, http://nhprof.com/) to manually view this count while debugging - but what I'd like to do is at runtime to get the actual number of calls to the database NHibernate is making so I can throw an exception if it's a ridiculous number like 50 or 300 (exact number to be determined).
This would be an indication to the developer that he/she needs to use 'Eager' and 'Future' and tweak the NHibernate code so hundreds of calls are not being made to the database.
Below I have an example where I'm seeing 284 calls being made to the database -
We can fix this code - so I'm not looking for a solution on how to make this NHibernate code better. I would like instead to implement a system that would notify developers they need to tweak the Nhibernate code.
Example - suppose we have the following model/db -
customer
customeraddress
order
orderstate
orderDetail
The code below makes one select call for each order detail to each of the related tables, etc... With only 72 order details in the db, we end up with 284 calls made to the database.
var query = QueryOver.Of<OrderDetail>()
.Where(c => c.UpdateTime >= updateTime);
using (var context = _coreSessionFactory.OpenSession())
{
var count = query.GetExecutableQueryOver(context)
.ToRowCountQuery()
.FutureValue<Int32>();
var items = query
.OrderBy(a => a.UpdateTime).Desc
.Skip(index ?? 0)
.Take(itemsPerPage ?? 20)
.GetExecutableQueryOver(context)
.Fetch(c => c.Order.OrderState).Eager
.Fetch(c => c.Order.Customer.CustomerAddress).Eager
.Future();
return new
{
Typename = "PagedCollectionOfContract",
Index = index ?? 0,
ItemsPerPage = itemsPerPage ?? 20,
TotalCount = count.Value,
Items = items.ToList().Select(c => new
{
Typename = "OrderDetail",
c.Id,
OrderId = c.Order.Id,
OrderStateAffiliates = c.Order.OrderStates.First(n => n.Name == StateNames.California).AffiliateCount,
CustomerZipCode = c.Order.Customer.CustomerAddresses.First(n => n.StateName == StateNames.California).ZipCode,
CustomerName = c.Order.Customer.Name,
c.DateTimeApproved,
c.Status
})
.ToArray()
};
}
It's not important for this order/customer model to be understood and to improve it - it's just an example so we get the idea on why I need to get the number of calls NHibernate makes to the db.
The SessionFactory can be configured to collect statistics. E.g. the number of successful transactions or the number of sessions that were opened.
This Article at JavaLobby gives some details.
You can use log4net to gather that info.
Logging NHibernate with log4net

Join Collection of Objects with LINQ to SQL

Is this even possible? It seems like I should be able to.
This is my issue. I need to run a web service method from a 3rd party to get a collection of available items where I need the ID and a Status property. Then I have method using LINQ to SQL that retrieves the items that are current.
What I need to do is retrieve the items that are current and available. I can connect them through ID BUT I also need the Status returned from the web service method.
Ideally, my final results will be the same results as from the LINQ to SQL method plus the Status property from the web service method.
Any assistance would be appreciated. Thanks!
Below is what I want to do. Have a method that takes in the list of objects from the web service and join with the existing query.
public List<Items> GetItems(List<AvailableItems> availList)
{
var result = (from c in dataContext.items
where c.status == "current"
select c;
return result;
}
public List<Item> GetItems(List<AvailableItems> availList)
{
var result = (from c in dataContext.items.AsEnumerable())
join a in availList on a.id equals c.id
where c.status == "current"
select c;
return result.ToList();
}
Re-Edit:
I typically extract the ids as a lookup list, and do the following:
public List<Items> GetItems(List<AvailableItems> availList)
{
var availableItemIds = availList.Select(a => a.Id).ToList();
var items = (from item in dataContext.items
where availableItemIds.Contains(item.Id)
where item.status == "current"
return items;
}