No coercion operator error with Linq query with Select new - linq

I'm using UWP, Sqlite and Linq to make ObservableCollections to bind to my XAML Listviews. No problems thus far.
Next I like to have the results of a join query into a List, also to bind to a Listview.
This results in an error even with the simplified code below:
public class BooksAndSeries
{
public int PublYear { get; set; }
public string SeriesName { get; set; }
public string Title { get; set; }
}
public static List<BooksAndSeries> SelBooksSeries { get; set; }
public static void LoadSearchedBooks()
{
using (CatDataContext catDB = new myBooks.Model.CatDataContext())
{
var SearchedBooks = from Book bb in catDB.Books
select new BooksAndSeries { PublYear = bb.PublYear, Title = bb.Title };
SelBooksSeries = new List<BooksAndSeries>(SearchedBooks);
}
}
The query gives the error:
System.InvalidOperationException
HResult=0x80131509
Message=No coercion operator is defined between types 'myBooks.GenModule+BooksAndSeries' and 'myBooks.Model.Book'.
Source=
StackTrace:
I'm using the latest Microsoft VS Community edition and Microsoft.EntityFrameworkCore.Sqlite 1.1.5.

Related

I get an error when use Odata query with contains

Here is controller code
[EnableQuery]
public IQueryable<Product> Get()
{
var productRepository = new ProductRepository();
return productRepository.Retrieve().AsQueryable();
}
Here is Retrieve() method
internal List<Product> Retrieve()
{
var filePath = HostingEnvironment.MapPath(#"~/App_Data/product.json");
var json = System.IO.File.ReadAllText(filePath);
var products = JsonConvert.DeserializeObject<List<Product>>(json);
return products;
}
And Product class
public class Product
{
public string Description { get; set; }
public decimal Price { get; set; }
public string ProductCode { get; set; }
public int ProductId { get; set; }
public string ProductName { get; set; }
public DateTime ReleaseDate { get; set; }
}
Other filters like $filter=Price+gt+6 or $top=4 and $skip=1 work fine. WebApi.OData package version=5.7.0
Error:
"The query specified in the URI is not valid. An unknown function with name 'contains' was found.
substringof() is a V3 function while contains() is a V4 function.
Try contains:
$filter=contains(Name,'value')
You are probably using an OData library package for OData version 3, but contains is a version 4 function. You can either query with the substringof function defined in version 3, or switch to a package that supports OData version 4.

MongoDB C# 2.0 - LINQ query alternative to AsQueryable

Here's what my model looks like
public class Bios
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("init")]
public string Init { get; set; }
[BsonElement("name")]
public string Name { get; set; }
}
With MongoDB C# driver 1.10, I'm able to do the following and get the right results. I get a string list of initials.
private static IEnumerable<string> InitList(MongoCollection mongoCollection)
{
return mongoCollection.AsQueryable<Bios>().Select(b => b.ResAnInit);
}
However, I upgraded the driver to 2.0.1 and tried to get the same results. With the help of Resharper, I modified the method to this:
private static async Task<IEnumerable<string>> InitList(IMongoCollection<Bios> mongoCollection)
{
return await mongoCollection.Find(x => x.Init != null)
.Project(Builders<Bios>.Projection.Include(y => y.Init).Exclude("_id"))
.ToListAsync();
}
I get errors now. How can I fix this to do what I did with C# driver 1.10?

Telerik OpenAccess - Mapping Varchar to Int

I'm trying to run an integer comparison (for instance greater than or less than) using OData on a value that is set to be a type of varchar in the database. Crossing out the solution of changing the database field to be a type of int, as it's not preferred in my specific case, is there a way to tell Telerik OpenAccess to convert the field to a type of integer when executing either the query or the mappings?
Thanks in advance.
It is similar with this one: Handling Dates with OData v4, EF6 and Web API v2.2
Add one more proerpty:
public partial class Title
{
public int Id { get; set; }
public string Name { get; set; }
public string StringProperty { get; set; }
}
public partial class Title
{
[NotMapped]
public int IntProperty
{
get
{
return StringProperty==null?0;Int32.Parse(StringProperty);;
}
set
{
StringProperty = value.ToString();
}
}
}
Update the model:
public static IEdmModel GetModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
EntityTypeConfiguration<Title> titleType= builder.EntityType<Title>();
titleType.Ignore(t => t.StringProperty);
titleType.Property(t => t.IntProperty ).Name = "MyProperty";
builder.EntitySet<Title>("Titles");
builder.Namespace = typeof(Title).Namespace;
return builder.GetEdmModel();
}

error in linq cannot convert from 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Linq.IQueryable<AnonymousType#2>

Contain has error:
error in linq cannot convert from
'System.Collections.Generic.IEnumerable' to
'System.Linq.IQueryable
Why?
public class ListQuestionAssessor
{
public string sum { get; set; }
public int QuestionsID { get; set; }
public int AssessorID { get; set; }
public int AssessID { get; set; }
}
List<ListQuestionAssessor> objList = new List<ListQuestionAssessor>();
var lisaAddAssessor = (from p in objList
where
!
(from assessor in ObjNotIn
select new
{
assessor.id
}).Contains(new { p.QuestionsID })
select new QuestionAssessor()
{
QuestionsID = initQuestionerId
}).ToList();
I would say that the problem is that you are trying to check
.Contains(new { p.QuestionsID })
Contains is expecting a parameter of the same type as the collection. and since the collection is anonymous, this is probably what caused the error.
rewrite it as
.Any(a => a.id == p.QuestionsID)

Linq trowing Exceptions

I create a project where I use EF with LINQ and Model first. So, based on my edmx I created my Database and also my classes.
So I got some problems. I created a Click to test if my code is working.
protected void btnSearch_Click(object sender, EventArgs e)
{
ZUser Zusr = new ZUser();
List<ZUser> lst = Zusr.ListAll();
// Zusr.Id = 1;
string test = "";
foreach (ZUser item in lst)
{
test = item.Name;
}
lblName.Text = test;
}
So in my ZUser Class (Controller) I did the following code:
[Serializable]
public class ZUser : User
{
String connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
public List<ZUser> ListAll()
{
List<ZUser> lstUser = new List<ZUser>();
using (DataContext db = new DataContext(connString))
{
Table<User> Users = db.GetTable<User>();
var query =
from usr in Users
where usr.Name == "Test"
select usr;
foreach (ZUser usr in query)
lstUser.Add(usr);
}
return lstUser;
}
}
And my Model (Class generated by my edmx)
namespace System.Model
{
//[Table]
public partial class User
{
public int Codigo { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public DateTime Created { get; set; }
public DateTime LastLogin { get; set; }
}
}
Problems
If I don't let the [Table] in my Model class (I added that) I got this error. I'm not sure if this is the right way to correct it.
The type '{0}' is not mapped as a Table.
After "fixing" the problem from above. I got this new one in my foreach (ZUser usr in query).
The member '{0}.{1}' has no supported translation to SQL.
I don't know how to fix or create a workaround this one.
Amazing, this feature of linq!
Really intresting!
After some searches on msdn and test it in application,
maybe you miss the Column attribute over all single class members:
[Column(CanBeNull = false, DbType = "int")]
And maybe you must uncomment the Table attribute on top of User declaration
Hope this help!

Resources