Explicit construction of entity type ### in query is not allowed - windows-phone-8

I use a Windows phone 8, MVVM + SQL Server CE 3.5 database
In folder model I have a declaration of table <TblCollections>
In folder ViewModel have this code for getting the collection.
public IEnumerable<TblCollections> GetTblCollections()
{
using (DbContext db = new DbContext(DbContext.ConnectionString))
{
var query = from collection in db.TblCollections
select new TblCollections
{
a = (string)collection.a,
b = (int)collection.b,
id = (int)collection.id,
};
IEnumerable<TblCollections> _TblCollections = query.ToList();
return _TblCollections;
}
}
I receive error on query.ToList();
Explicit construction of entity type "TblCollections" in query is not allowed
Why?

Do not specify class and Try this(Untested code):
IEnumerable<TblCollections> query = from collection in db.TblCollections
select new
{
a = (string)collection.a,
b = (int)collection.b,
id = (int)collection.id,
};

Related

Cannot Create a Group, Invalid Scope

I am trying to create a group with the following dot.net code:
var groupDef = new Group()
{
DisplayName = name,
MailNickname = name + " " + GetTimestamp(),
Description = "Group/Team created for testing purposes",
Visibility = "Private",
GroupTypes = new string[] { "Unified" }, // same for all teams
MailEnabled = true, // same for all teams
SecurityEnabled = false, // same for all teams
AdditionalData = new Dictionary<string, object>()
{
["owners#odata.bind"] = owners.Select(o => $"{graphV1Endpoint}/users/{o.Id}").ToArray(),
["members#odata.bind"] = members.Select(o => $"{graphV1Endpoint}/users/{o.Id}").ToArray(),
}
};
// Create the modern group for the team
Group group = await graph.Groups.Request().AddAsync(groupDef);
I am getting a "Method not allowed." error thrown on the last line shown (Group group = await ...).
The scope parameter for the auth provider contains "Group.Read.All Group.ReadWrite.All".
If I add Group.Create to the scope I get an error stating the scope is invalid. Reducing the scope to just "Group.Create" also gives an error.
It certainly appears that I cannot create a group without Group.Create in the scope, but that throws an error at sign in.
Microsoft.Graph is version 3.19.0
Microsoft.Graph.Core is version 1.22.0
I ended up serializing the object and making the Http call with my own code. Basically, something like this:
string json = JsonConvert.SerializeObject(groupDef, jsonSettings);
Group group = HttpPost<Group>("/groups", json);
No permissions were changed.

How to call stored procedure in Entity Framework Core with input and output parameters using mysql

I am using ASP.net Core 2.2 with Entity Framework core 2.2.6 and Pomelo.EntityFrameworkCore.MySql 2.2.0 for connectivity with MySQL, I have a stored procedure which takes 3 input parameters and 1 output parameter. I am able to call it in MySQL workbench like
CALL GetTechniciansByTrade('Automobile', 1, 10, #total);
select #total;
Now I want to call this using entity framework core, the code I am currently using is
var outputParameter = new MySqlParameter("#PageCount", MySqlDbType.Int32);
outputParameter.Direction = System.Data.ParameterDirection.Output;
var results = await _context.GetTechnicians.FromSql("Call GetTechniciansByTrade(#MyTrade, #PageIndex, #PageSize, #PageCount OUT)",
new MySqlParameter("#MyTrade", Trade),
new MySqlParameter("#PageIndex", PageIndex),
new MySqlParameter("#PageSize", PageSize),
outputParameter).ToListAsync();
int PageCount = (int)outputParameter.Value;
Exception I am getting currently is
Only ParameterDirection.Input is supported when CommandType is Text (parameter name: #PageCount)
Can you try below things.
Use exec instead of call
var results = await _context.GetTechnicians.FromSql("EXEC GetTechniciansByTrade(#MyTrade, #PageIndex, #PageSize, #PageCount OUTPUT)"
Select PageCount in stored procedure
I got information from this github issue.
I found the solution using #matt-g suggestion based on this Question.
I had to use ADO.net for this as
var technicians = new List<TechnicianModel>();
using (MySqlConnection lconn = new MySqlConnection(_context.Database.GetDbConnection().ConnectionString))
{
lconn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = lconn;
cmd.CommandText = "GetTechniciansByTrade"; // The name of the Stored Proc
cmd.CommandType = CommandType.StoredProcedure; // It is a Stored Proc
cmd.Parameters.AddWithValue("#Trade", Trade);
cmd.Parameters.AddWithValue("#PageIndex", PageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.AddWithValue("#PageCount", MySqlDbType.Int32);
cmd.Parameters["#PageCount"].Direction = ParameterDirection.Output; // from System.Data
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
technicians.Add(new TechnicianModel()
{
City = reader["City"].ToString(),
ExperienceYears = reader["ExperienceYears"] != null ? Convert.ToInt32(reader["ExperienceYears"]) : 0,
Id = Guid.Parse(reader["Id"].ToString()),
Name = reader["Name"].ToString(),
Qualification = reader["Qualification"].ToString(),
Town = reader["Town"].ToString()
});
}
}
Object obj = cmd.Parameters["#PageCount"].Value;
var lParam = (Int32)obj; // more useful datatype
}
}

How to Add a shapefile data to postgis(postgres) using c#

am trying to add shapefile data to postgis using c#
string path = browse_path.Text;
ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe");
Process p = new Process();
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
p = Process.Start(startInfo);
string chgdir = #"chdir " + #"C:\Program Files\PostgreSQL\9.4\bin\";
p.StandardInput.WriteLine(chgdir);
string pass = #"set PGPASSWORD=postgres";
p.StandardInput.WriteLine(pass);
string cmd = #"shp2pgsql -I -s 4326 " + path + " public.states | psql -U postgres -d postgres";
p.StandardInput.WriteLine(cmd);
p.WaitForExit();
p.Close();`
and for waiting almost 7-8 mins its not working. my shp file is 160 kb only.. but the command is working fine if i run it in the cmd rather then using code..
This is a function I wrote to import shapefiles to PG. It uses Nuget packages CliWrap and Npgsql and I just copied shp2pgsql and its dependencies to a project folder 'Tools' so it can be run on a machine that doesn't have PostgreSQL installed. Its a bit messy and you might need to add error handling but it worked for my needs.
public async static Task<bool> OutputSHPtoPSGLAsync(string shpfile, string host, string user, string pwd, string db, string schema = "public", bool dropIfExists = true, string table = "[SHPNAME]")
{
FileInfo shp = new FileInfo(shpfile);
if (!shp.Exists) return false;
if (table == "[SHPNAME]") table = Path.GetFileNameWithoutExtension(shpfile).ToLower();
string args = string.Format("{0} {1}.{2}", shpfile, schema, table);
Command cli = Cli.Wrap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"tools\shp2pgsql.exe")).WithArguments(args);
ExecutionResult eo = await cli.ExecuteAsync();
string sql = eo.StandardOutput;
if (dropIfExists) sql = sql.Replace("CREATE TABLE", string.Format("DROP TABLE IF EXISTS \"{0}\".\"{1}\";\r\nCREATE TABLE", schema, table));
string constring = string.Format("Host={0};Username={1};Password={2};Database={3}", host, user, pwd, db);
using (NpgsqlConnection connection = new NpgsqlConnection(constring))
{
connection.Open();
new NpgsqlCommand(sql, connection).ExecuteNonQuery();
}
return true;
}
I was looking at NetTopologySuite which has type definitions compatible with Npgsql and PostGIS but its all still pre-release and couldn't be bothered working it out.

not able to call methods after decoding from json

I have a Lua class like below. I am using json to serialize the object and put it in a key value store. I am able to serialize the object and put it in the key value store successfully but i am not able to call any methods of the object after i retrieve the object from the key value store. I understand the json module skips the methods while encoding and my object does not have methods after decoding.
Is there a way to append methods to the class after i decode the object from json to lua ? some thing similar to function pointers in C language.
local class_name = "user_object";
user_object = {}; --user class
function user_object.new (mobile, password, uid)
local self = {};
self.mobile = mobile;
self.uid = uid; -- generate a uid which is a running number.
self.password = password;
self.messages_sent = 0;
self.put_request_count = 0;
self.get_request_count = 0;
self.last_time_active = "";
self.get_tickets = {};
self.put_tickets = {};
self.group_message_stream = {};
self.group_ownerships = {}; -- group names which he is owner of
self.group_memberships = {}; -- group names which he is member of
self.sent_poke_count = 0;
self.sent_poke_stream = {};
self.recv_poke_count = 0;
self.recv_poke_stream = {};
function self:add_put_ticket(ticketid)
table.insert(self.put_tickets, ticketid);
self:incr_put_count();
self:save();
return;
end
function self:add_get_ticket(ticketid)
table.insert(self.get_tickets, ticketid);
self:incr_get_count();
self:save();
return;
end
Function in Lua are first class objects, you can store a function in any variable. The line
function self:add_put_ticket(ticketid)
is equivalent to
self.add_put_ticket = function (self, ticketid)
From there, it should be obvious what to do: define your desired methods where they are accessible and assign them to the appropriate fields after deserialization
You can do this with metatables.
user = { name = 'ponzao' } -- Just a table with values.
User = {} -- Table containing the functions.
function User:allCapsName() return self.name:upper() end -- A method.
setmetatable(user, {__index = User}) -- For unavailable keys all calls are dispatched to User.
print(user:allCapsName()) --> "PONZAO"

Convert SqlCommand Output to List<MyType>?

I am using an ADO.NET SqlCommand with a single SqlDbType.Structured parameter to send a table-valued parameter to a sproc. The sproc returns many rows, which I need to get into a strongly-Typed List of . What is the best way to convert the result set (whether DataTable from a DataAdapter or DataReader bits) into List?
Thanks.
You can use LINQ with a DataReader:
var list = reader.Cast<IDataRecord>()
.Select(dr => new YourType { Name = dr.GetString(0), ... })
.ToList();
The most efficient way is using datareader:
var items = new LinkedList<MyClass>();
using(var connection = GetConnection()) {
using(var cmd = connection.CreateCommand()){
cmd.CommandText = "... your SQL statement ...";
// ... add parameters
cnn.Open();
using(var reader = cmd.ExecuteReader()) {
// accessing values via number index is most efficient
//gets index of column with name "PrimaryKey"
var ndxPrimaryKey = reader.GetOrdinal("PrimaryKey");
var ndxColumn1 = reader.GetOrdinal("Column1");
var ndxColumn2 = reader.GetOrdinal("Column2");
while(reader.Read()) {
var item = new MyClass();
// returns value of column "PrimaryKey" typed to nullable Guid
item.PrimaryKey = reader.GetValue(ndxPrimaryKey) as Guid?;
item.Column1 = reader.GetValue(ndxColumn1) as string;
item.Column2 = reader.GetValue(ndxColumn2) as int?;
items.AddLast(item);
}
}
cnn.Close();
}
}
return items;
i think you can use Dapper to convert a query to a class.
for more information see my answer in this link