Query LINQ - Could not find an implementation of the query pattern - c#

I created a table in my designer view with 4 columns. I'd like to add others columns manually (because it'll be add according the data stored in DB).
I would like to create the link between the data from DB and the table so I did this :
private void LoadSiteDataSource()
{
CVaultDataSource.Rows.Clear();
if (this.Site != null)
{
var sitesDB = from sites in this.Site
select sites.KEY;
foreach (var item in sitesDB)
{
CVaultDataSource.Rows.Add(item);
}
}
}
But I have this error :
Could not find an implementation of the query pattern for source type System.ComponentModel.ISite. 'Select not found'.
I've look the differents topics about this error but I could not find something to fix it.
I'm already using this function which works :
private void LoadDataSource()
{
CVaultDataSource.Rows.Clear();
if (this.BaseFilters != null)
{
var filters = from filterBase in this.BaseFilters
orderby filterBase.EVPTCODE
select new object[] { filterBase.CVAULTCODE, filterBase.EVPTCODE, filterBase.EVPTDESIGNATION, filterBase.DURATION, filterBase.ETDTIME };
foreach (var item in filters)
{
CVaultDataSource.Rows.Add(item);
}
}
}
Does someone know why it does not work ?

I just forget to declare this :
public List<SITE> Sites { get; private set; }
That's why it did not work.

Related

SQLite Xamarin Forms Database Table to ListView

Hello, I'm currently trying to show a table in an Android base App. however, my question is regarding:
var db = new SQLiteAsyncConnection(Database.DatabasePath.DB_Path);
foreach ( var N in db.Table<Database.Inventory>() )
{
InventoryItems.Add(new Store_Listing { Id = N.Id,
Description = N.Description, Style = N.Style });
This part of the code that is taking an error of:
foreach statement cannor operate on variables of type 'AsyncTableQuery< ... > ' because 'AsyncTableQuery< ... >' does not contain a public instance for 'GetEnumerator'
foreach ( var N in db.Table<Database.Inventory>() ) "
I have looked into the Database.Inventory Class, and it is set to public class, and all the elements are exactly as the SQLite database (Type 3) table.
Honestly I don't really know what is wrong.
There are no issues connecting the database .db3, but these error is unknown to me since I'm quite new to the SQLite and Android.App Dev.
This is the code for the Database.Inventory:
using System;
using System.Collections.Generic;
using System.Text;
using SQLite;
namespace Inventory.Database
{
[Table("Inventory")]
public class Inventory
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Description { get; set; }
public string Style { get; set; }
}
}
Thank You for your feedback in advance.
You are calling a new instance of SQLiteAsyncConnection, which uses async instructions for all its methods (where needed). In the SQLite NuGet source code, you will find that Table<T> returns a variable of type AsyncTableQuery. AsyncTableQuery does not implement or inherit anything. It's a stand-alone class, which means it cannot access the method GetEnumerator that it is expecting to access for a foreach statement.
So, in your code where you have:
var db = new SQLiteAsyncConnection(Database.DatabasePath);
foreach ( var N in db.Table<Database.Inventory>() ) // Table<T> does *not* return a List<T>!!
{
InventoryItems.Add(new Store_Listing
{
Id = N.Id,
Description = N.Description,
Style = N.Style
});
}
You're trying to access what you think is a List, but is actually an AsyncTableQuery.
How to get around this
If you look at the AsyncTableQuery class, it has a ToListAsync method, which converts the AsyncTableQuery object to a List<T> object. Simply calling this will convert your Table<T> to a List<T> like so:
var db = new SQLiteAsyncConnection(Database.DatabasePath);
var myList = await db.Table<Database.Inventory>().ToListAsync();
// TODO: Add a null or empty check to prevent NullExceptions.
foreach(var N in myList)
{
// Do your stuff
}
var results = await db.Table<Database.Inventory>();
var query = conn.Table<Database.Inventory>();
query.ToListAsync().ContinueWith((t) =>
{
foreach (var N in t.Result)
{
// code from your foreach loop
}
});

Missing a cast in a linq query for a controller

I am new with c# controllers and I am trying to join two entities with a LINQ query. But I am getting a 'missing a cast' error message as shown below that I don't understand and it does not help me to correct the error.
The controller looks like:
public class SoonDueReportsController_simple : BaseODataController
{
public SoonDueReportsController_simple(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]
public SoonDueReportsController_simple Get()
{
var falligkeiten = UnitOfWork.GetAll<Fälligkeiten>();
var betriebe = UnitOfWork.GetAll<Betriebe>();
var query = (from betrieb in betriebe.AsQueryable()
join fallig in falligkeiten.AsQueryable()
on betrieb.ID equals
fallig.Betrieb_ID
where fallig.Fälligkeit_Erledigt_Datum == null
&& betrieb.Aktiv == true
select new
{
BetriebId = betrieb.ID,
FalligkeitObject = fallig.Fälligkeit_Objekt
});
return query;
}
}
This type of controller I have used with success for single entities (tables from an sql db) to display static data in a kendo grid. But I fail when I try to join two tables as shown above. If someone could help me with this problem I'd appreciate it very much.
Regards, Manu
You select a collection of anonymous objects
select new
{
BetriebId = betrieb.ID,
FalligkeitObject = fallig.Fälligkeit_Objekt
});
And want the method to return a instance of certain type. C# is the strongly typed language without type inference, which means you have to specifically create objects of a certain type or interface if you want to return them.
Also, you are have the controller type itself to be returned from the Get method. This makes no sense. I actually do not know what you want to do but may be this would work:
public class SoonDueReportsController_simple : BaseODataController
{
public SoonDueReportsController_simple(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<SomeModel> Get()
{
var falligkeiten = UnitOfWork.GetAll<Fälligkeiten>();
var betriebe = UnitOfWork.GetAll<Betriebe>();
var query = (from betrieb in betriebe.AsQueryable()
join fallig in falligkeiten.AsQueryable()
on betrieb.ID equals
fallig.Betrieb_ID
where fallig.Fälligkeit_Erledigt_Datum == null
&& betrieb.Aktiv == true
select new SomeModel
{
BetriebId = betrieb.ID,
FalligkeitObject = fallig.Fälligkeit_Objekt
});
return query;
}
}
public class SomeModel
{
public int BetriebId { get; set; }
public string FalligkeitObject { get; set; }
}
Please bear in mind that there are no such things as "C# controllers". You are working with OData, so I would recommend you to look at some OData resources, there are plenty of examples out there.
And one last thing, don't get me wrong, but it does not help giving properties, types and other identifiers German names. People would have hard time trying to understand your code.
The exception explains to you the problem exactly. You're wanting to return a type of 'SoonDueReportsController_simple' and yet you are returning a Queryable where a' is your new { ..., ... } object.
I like the suggestion given to make a strong typed object and fill it but you can also return a dynamic type.
This code works to explain:
private dynamic Get() => new { Name = "SomeName", Age = 31 };
private void TestGet()
{
var obj = Get();
var name = obj.Name;
var age = obj.Age;
}

Pass linq query result to viewmodel

In my MVC web application, I have linq query that feth the record from database, I want to display that record on view using viewmodel. I have tried with following code.
[HttpGet]
public ActionResult CreatePDF()
{
RentalAgreementEntities db = new RentalAgreementEntities();
String strSession1 = "39726-10275-6027589725",strStatus = "Y",strUserType = "L";
var q = (from um in db.User_Master
join ut in db.UserType_Master on um.US_SerialNo.ToString() equals ut.UT_UserNo
join pu in db.PropertyUser_Master on ut.UT_SerialNo.ToString() equals pu.PU_UserNo
join pr in db.Property_Master on pu.PU_PropertyNo equals pr.PR_SerialNo.ToString()
where pr.PR_MakerID == strSession1
&& ut.UT_Status == strStatus
&& ut.UT_UserType == strUserType
select new
{
um.US_FirstName,
um.US_LastName
}
).AsEnumerable().Select(um => new User_Master {
US_FirstName = um.US_FirstName.ToString(),
US_LastName=um.US_LastName
}).ToList();
var myviewmodel=new viewmodelPDF()
{
lsusermaster=q.ToList();
}
return View("pdfgenerationvw",myviewmodel);
}
I also created viemodel to manage all model's for to display on a view (Here, Just one model access code).
public class viewmodelPDF
{
public List<User_Master> lsusermaster { get; set; }
}
My model class, for which I am going to fetch record from database.
public partial class User_Master
{
public string US_FirstName { get; set; }
public string US_LastName { get; set; }
public int US_SerialNo { get; set; }
}
//Other Models
Now my problem is that, In my action code , when I am trying to assign query result to the lsusermaster of viewmodel then it gives compiler error as belows.
I don't know, why this compile error is thrown, How can I assign query result to viemodel property?
Try this:
var myviewmodel=new viewmodelPDF()
{
lsusermaster=q.ToList()
};
When you are using an object initializer in C#, you can't use ; between the properties, you use it at the end of the initializer
So just remove the ; (or use a ,, as suggested), and move it to the end of the initializer block
var myviewmodel=new viewmodelPDF()
{
lsusermaster=q.ToList()
};
Using a , works even if there are no more properties... it "looks" bad, but it makes easier to add new properties should you ever need them... if the code is final, I'd not use it, but that's personal preference

How to get all PageTemplate that contains a specific component?

I have a pagetemplate called ArticlePageTemplate. This ArticlePageTemplate contains a component called Articles. The Article component has data field called Header, SubHeader, Date, and Content.
Presentation details of ArticlesPageTemplate
Using Lucene in sitecore 8. How do I get all ArticlePageTemplate that contains an Article component with the value of "News" in subheader of Article component.
Sitecore structure:
Here is my code
public class LuceneSearchService : ILuceneSearchService, IDisposable
{
bool disposed = false;
// Instantiate a SafeHandle instance.
SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
private IProviderSearchContext _SearchContext;
private ISearchIndex _Index;
private string _IndexName = "sitecore_web_index";
public string IndexName
{
get { return _IndexName; }
set { _IndexName = value; }
}
public LuceneSearchService()
{
_Index = ContentSearchManager.GetIndex(this.IndexName);
_SearchContext = _Index.CreateSearchContext();
}
public IQueryable<SearchResultItem> PerformSearch(string searchPath)
{
var searchQuery = _SearchContext.GetQueryable<SearchResultItem>()
.Where(i => i.Path.StartsWith(searchPath));
return searchQuery;
}
public IQueryable<SearchResultItem> PerformSearch(string searchPath, string templateName)
{
var searchQuery = PerformSearch(searchPath).Where(x => x.TemplateName == templateName);
return searchQuery;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
_SearchContext.Dispose();
_Index.Dispose();
}
// Free any unmanaged objects here.
//
disposed = true;
}
}
Code implementation
public void SearchArticles()
{
var articles = SearchService.PerformSearch("/sitecore/content", "ArticlePageTemplate").ToList();
foreach (var article in articles){
var articleName = article;
}
}
I can get all the ArticlesPageTemplate using the code above but I can't filter it to get only those ArticlePageTemplate that contains an Article component in which Article component's subheader is "news".
I do not know how to get the articles component of ArticlePageTemplate so I could add them to my search query in lucene.
Any advice is appreciated.
Note:
The datasource of ArticlesComponent may change so it is not always a child of ArticlesPageTemplate.
UPDATE (09/11/2015)
I tried what Richard suggested but it does not work.
var articles = SearchService
.PerformSearch<ArticleResultItem>("/sitecore/content", "ArticlePageTemplate")
.Where(item => item.SubHeader == "News").ToList();
Using the above query does not yield any result but using the below query returns a result but it retrieves ArticleComponent instead of ArticlePageTemplate.
var articles = SearchService
.PerformSearch<ArticleResultItem>("/sitecore/content"
.Where(item => item.SubHeader == "News").ToList();
SOLUTION:
Computed fields works. See VisualizationField.cs from the link below:
https://gist.github.com/techphoria414/7604814
I can see two approaches that you can go with here:
Build a 'computed field' for the Article component subheader field. You would set this up so that the index is configured to look for this component on an item with the ArticlePageTemplate template and compute the subheader value into the index. This essentially makes the index think that the subheader field is actually a field on ArticlePageTemplate item. Then you can do a regular search on the index.
Find the reference pages for a component. In this scenario, you search the index for the components (not ArticlePageTemplate), and if you can depend on your folder structure and you do not have re-use across pages, you can then just grab the parent page of any search result. (item.Parent.Parent, in your example structure)
UPDATE: Some links for computed fields:
http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2013/03/sitecore-7-computed-index-fields.aspx
https://gist.github.com/techphoria414/7604814
You would need to create a custom class that allows you to filter on your field, you can base it off the SearchResultItem class.
So something like:
public class ArticleResultItem : SearchResultItem
{
[IndexField("SubHeader")]
public string SubHeader { get;set; }
}
Then if you change your PerformSearch method to take a generic based of SearchResultItem, you can filter using that field in your calling method.
public IQueryable<T> PerformSearch<T>(string searchPath)
where T: SearchResultItem
{
var searchQuery = _SearchContext.GetQueryable<T>()
.Where(i => i.Path.StartsWith(searchPath));
return searchQuery;
}
public IQueryable<T> PerformSearch<T>(string searchPath, string templateName)
where T: SearchResultItem
{
var searchQuery = PerformSearch<T>(searchPath).Where(x => x.TemplateName == templateName);
return searchQuery;
}
And then you would call it like this:
public void SearchArticles()
{
var articles = SearchService
.PerformSearch<ArticleResultItem>("/sitecore/content", "ArticlePageTemplate")
.Where(item => item.SubHeader == "News").ToList();
foreach (var article in articles){
var articleName = article;
// Do something with the list here....
}
}

Inset an object inheriting from a database object does not work in EF

I have this object:
public class OrderViewModel : ORDERS
{
public IEnumerable<SelectListItem> mCountryList { get; set; }
public OrderViewModel()
{
List<string> listCountries = new List<string>();
XmlDocument doc = new XmlDocument();
doc.Load(HttpContext.Current.Server.MapPath("~/App_Data/countries.xml"));
var xmlNodeList = doc.SelectNodes("//country");
if (xmlNodeList != null)
{
listCountries.AddRange(from XmlNode node in xmlNodeList select node.InnerText);
}
mCountryList = new SelectList(listCountries);
}
public void SetCountry(string _country)
{
foreach (var selectListItem in mCountryList.Where(_selectListItem => _selectListItem.Value == _country))
{
selectListItem.Selected = true;
}
}
}
Which inherits from ORDERS, an object contained in my database:
public DbSet<ORDERS> ORDERS { get; set; }
because I wanted to create a new ORDERS at this point, but needed the list of countries for user purpose. However when I try to create my order like this:
using (MyEntity db = new MyEntity())
{
if (db.Database.Connection.State == ConnectionState.Closed)
{
db.Database.Connection.Open();
}
OrderViewModel orderToReturn = new OrderViewModel();
db.ORDERS.Add((ORDERS)orderToReturn);
db.SaveChanges();
}
I get the following error:
Mapping and metadata information could not be found for EntityType 'MyApp.ViewModels.OrderViewModel'.
What's happening? How can I correct this?
I had similar issues a while back. Using Visual Studio to generate a model for my DB led to all the classes being partial, so rather than inherit to add extra functionality (which I tried and ended up in a mess with) I just added an extra partial for each class I wanted to extend. This keeps EF happy and also means your extra code isn't lost when the model's next updated.

Categories