Execute complex raw SQL query in EF6 - sql-server

I am developing a web api using Entity Framework 6. I have to execute a complex SQL query which is getting data from multiple tables as shown in the code. I have tried but get the following error:
The data reader has more than one field. Multiple fields are not valid
for EDM primitive or enumeration types.
The query successfully return data in SSMS Query Analyzer.
[HttpGet]
public IHttpActionResult getJobNo(string cmpCode, string branchCode)
{
string query = string.Format(
#"select
M.S1, M.S2, C.S2 As S30, M.S3, SC.S2 As S31, M.D1, M.S5,
JT.S2 As S32, M.S6, TM.S2 As S33, M.S10
from
MERTRM M, CMF C, CMFS SC, PMCD JT, PMCD TM
where
M.S100 = 'JOB' and M.S102 = '{0}' and
M.S108 = '{1}' and
M.S101 not in('U', 'C', 'F') and
M.S2 = C.S1 and C.S102 = '{0}' and
C.S100 = 'CC' and M.S3 = SC.S1 and SC.S102 = '{0}' and
C.S1 = SC.S109 and M.S5 = JT.S1 and JT.S102 = '{0}' and
JT.S100 = 'JTP' and M.S6 = TM.S1 and TM.S102 = '{0}' and
TM.S100 = 'TPM'",
cmpCode,branchCode);
var result = db.Database.SqlQuery<string>(query);
return Json(result.ToArray());
}
Since the query returns a list of records so when I tried as follows:
var result = db.Database.SqlQuery<IEnumerable<string>>(query).ToList();
It gave me the following error:
'System.Collections.Generic.IEnumerable`1[System.String]' may not be
abstract and must include a default constructor.
How can I execute this query?
Regards!

you must use a DAO/DTO type:
class MyDAOType {
public String S1 {get; set;}
public String S2 {get; set;}
//...
public String S10 {get; set;}
}
and the query
var result = db.Database.SqlQuery<MyDAOType>(query);

Probably the easiest way is to define your own class that has the same fields as returned SQL and use this class as output.
public class MyReport {
public string S1 { get; set; }
public string S2 { get; set; }
public string S30 { get; set; }
public string S3 { get; set; }
public string S2 { get; set; }
public string S31 { get; set; }
public string D1 { get; set; }
public string S5 { get; set; }
public string S32 { get; set; }
public string S6 { get; set; }
public string S33 { get; set; }
public string S10 { get; set; }
}
var result = db.Database.SqlQuery<MyReport>(query).ToList();

Related

Pass parameters to report Devexpress

Please tell me. Created 2 classes (Data Model)
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public string Department { get; set; }
public int Office { get; set; }
public string Position { get; set; }
public string Phone { get; set; }
public float Mobile { get; set; }
public string EMail { get; set; }
public string Login { get; set; }
public int idArm { get; set; }
}
and
public class arm
{
public int id { get; set; }
public string name { get; set; }
public string Detalis { get; set; }
}
I installed 2 GridControlls on the form
And through DataSet showed data
string connectionString = ConfigurationManager.ConnectionStrings["connectionSIPiT"].ConnectionString;
string command = "SELECT * FROM Users";
string command2 = "SELECT * FROM arm";
sqlConnection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(command2, sqlConnection);
SqlDataAdapter adapter1 = new SqlDataAdapter(command, sqlConnection);
DataSet dataset1 = new DataSet();
adapter.Fill(dataset1, "arm");
adapter1.Fill(dataset1, "Users");
DataColumn keyColumn = dataset1.Tables[0].Columns[0];
DataColumn foreignKeyColumn = dataset1.Tables[1].Columns[9];
dataset1.Relations.Add("armUsers", keyColumn, foreignKeyColumn);
armBindingSource.DataSource = dataset1;
armBindingSource.DataMember = "arm";
userBindingSource.DataSource = armBindingSource;
userBindingSource.DataMember = "armUsers";
gridControl1.DataSource = userBindingSource;
gridControl2.DataSource = armBindingSource;
How do I select a row in the main table GridControll. Send report data. Or pass the id of the main table to build the report? Can anyone come across such a task?
Make sure that the Modifiers property for the report parameter is set to Public or Internal
Use the GridView.GetRowCellValue method to get the ID column value of the focused record
The following assumes that you have a report called MyReport and it has a parameter called MyParameter.
var id = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["UserID"]));
var rpt = new MyNewReport();
rpt.MyParameter.Value = id; //Make sure the MyParameter's Modifiers property is set to Public or Internal.

Invalid column name exception thrown in .NET Core web api

I have two classes in my database which are defined as classes, fed into entity and then called from the API
The full method is below for the calls. The first call works fine, the second throws the exception
public async Task<ActionResult<List<QuizForms>>> GetQuiz([FromQuery]string id)
{
var form = await _context.QuizForms.Where(t=>t.QuizId == id).ToListAsync();
if (form == null)
{
return NotFound();
}
var elem = new List<Element>();
foreach(var e in form)
{
var data = await _context.Element.Where(t => t.ElementId == e.ElementId).ToListAsync();
elem.AddRange(data);
e.Element.AddRange(elem);
}
return form;
}
When the var data line is hit, an excception is thrown
Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'QuizFormsFormId'.
It looks like the name of the class and column name are being concatenated and the used as the query parameter.
The two classes look like this
public class QuizForms
{
[Key]
public int FormId { get; set; }
public string QuizId { get; set; } = "";
#nullable enable
public string? Title { get; set; }
public int? ElementId { get; set; }
public List<Element>? Element { get; set; }
public int? PreviousId { get; set; }
public int? NextId { get; set; }
#nullable disable
}
and
public class Element
{
[Key]
public int Id { get; set; }
public int ElementId { get; set; }
#nullable enable
public int? MathsId { get; set; }
public int? QuestionId { get; set; }
public int? InformationId { get; set; }
public int? AnswerId { get; set; }
#nullable disable
public string QuizId { get; set; } = "";
}
Is it because I'm not using Id for the primary key or do I need to do something else so the class and property aren't concatented like this?

Resolve an issue for Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException

I have an issue during an insert operation into the table using Entity Framework Core.
_context.Entry(item).State = EntityState.Added;
var r = await _context.ServiceWorkOrders.AddAsync(item);
_context.SaveChangesAsync(); <-- (fails)
Some context when dealing with this issue.
The table is owned by client so I have to work around this issue
The table to insert into, contains triggers and stored procedures set to run after Insert/Update/Delete operations.
The table have relationship properties (Foreign keys)
The table's primary key is set to auto-increment, hence the primary key field of the inserting entity is set to 0, along with the fields that is required during this insert.
I am trying to use Stored Procedure directly using ExecuteSqlCommand, but I would prefer to use EF to manage the database access. Moreover, correct me if I am wrong, I would have to list all the optional parameters in the Stored Procedure in order to add the entity in to prevent writing into the wrong fields. Currently this method inserts the entity, but it writes on the wrong fields, even if I used SqlParameters("#named_field", value).
I have tried using the Synchronous method as well, but it gives the same exception.
The exception returned:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.'
edit:
Here is the entity model:
[Table("ASM_ServiceWorkOrder")]
public class ServiceWorkOrder: BaseEntity
{
[Key, Column(name: "ROWUID"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RowUID { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string CompanyID { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DocNumber { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string RevisionNumber { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string CustomerDirectoryID { get; set; }
[ForeignKey("CustomerLocation")]
public Int32? CustomerLocationRowUID { get; set; }
public AssetLocation CustomerLocation { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string WorkOrderType { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string IssueType { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string AssetItemCode { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string AssetSerialNo { get; set; }
[ForeignKey("AssetRegister")]
public int? AssetRegisterROWUID { get; set; }
public AssetRegister AssetRegister { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string ProjectDirectoryID { get; set; }
[Column(TypeName = "nvarchar(10)")]
public string Priority { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string Status { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string StatusForClient { get; set; }
public bool? Billable { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal? QuotedFee { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DueDate { get; set; }
[Column(TypeName = "nvarchar(240)")]
public string Description { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string ReportedBy { get; set; }
[Column(TypeName = "datetime")]
public DateTime? ReportedDate { get; set; }
[Column(TypeName = "nvarchar(35)")]
public string BusinessDataType { get; set; }
[Column(TypeName = "nvarchar(240)")]
public string DocRemarks { get; set; }
[Column(TypeName = "nvarchar(2000)")]
public string ErrorText { get; set; }
public Guid? RowGlobalUID { get; set; }
public Int32? HeaderROWUID { get; set; }
[Column(TypeName = "datetime"), DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? DateOfDocument { get; set; }
//[Timestamp]
//public byte RowVersion { get; set; }
//public IList<ServiceWorkOrderAttachment> Attachments { get; set; }
public IList<ServiceWorkOrderDetails> Details { get; set; }
}
Are u sure u created ITEM? And indicate table where u try save row?
If u wanna insert row in table u must create your item first.
f.ex:
var = new ServiceWorkOrders(){Column1=var1,Column2=var2 etc.};
await _context.ServiceWorkOrders.AddAsync<ServiceWorkOrders>(item);
await _context.SaveChangesAsync();

De serialize the JSON data in wpf

I have a url which return's json data in the following way
{"title":"Test Title","image_url":"http://i.imgur.com/aZO5Kol.jpg","random_window":2,"windows":{"1":{"title":"Random 1"},"2":{"title":"Other Window 2"}},"thankyou_url":"http://google.com"}
Now i want to De-serialize this so that i can write the conditions based on the data received.
I want achieve this
will have to print the image and Name which is received through JSON. And based on the number of windows i should show the windows
I have declared a class
public class JsonData
{
string title { get; set; }
string image_url { get; set; }
string random_window { get; set; }
string[] windows { get; set; }
string thankyou_url { get; set; }
}
and i have written like this
WebClient objWebClient = new WebClient();
var jss = new JavaScriptSerializer();
string strJsonURL = "url";
var vJsondata = string.Empty;
vJsondata = objWebClient.DownloadString(strJsonURL);
var data = jss.Deserialize<object>(vJsondata);
try
{
var x = ((IList)data).Cast<object>().Select(o => o.ToString()).ToList();
}
But getting this error:
Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'System.Collections.IList'.
It appears that windows is a Dictionary and not a string array as you have defined in JsonData. You'll have to test this but from what I can tell it should be more like this:
public class JsonData
{
string title { get; set; }
string image_url { get; set; }
string random_window { get; set; }
Dictionary<string, WindowData> windows { get; set; }
string thankyou_url { get; set; }
}
public class WindowData
{
string title { get; set; }
}

Subsonic 3.0.0.5 Migration Row Update

I want to update a table row and I have a following Code
void updatePrimaryPaymentAndSecondaryPaymentSourceTypes()
{
LookUpDetails lookUpDetail = new LookUpDetails();
var repo = new SimpleRepository("E2Lending", SimpleRepositoryOptions.RunMigrations);
lookUpDetail = repo.Single(80);
lookUpDetail.Col1Value = "My Checking Account";
repo.Update(lookUpDetail);
}
public class LookUpDetails
{
[SubSonicPrimaryKey]
public int LookUpDetailId {get; set;}
public int LookUpGroupId { get; set; }
public string Code { get; set; }
public int SortOrder { get; set; }
public string Col1Value { get; set; }
[SubSonicNullString]
public string Col2Value { get; set; }
[SubSonicNullString]
public string Col3Value { get; set; }
[SubSonicNullString]
public string Col4Value { get; set; }
[SubSonicNullString]
public string Col5Value { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
public Boolean IsActive { get; set; }
}
When I execute then repo.Update(lookUpDetail); shows me Null reference Exception.
Can you please tell me How I will be able to update a single record in a table?
Regards
I have the very same problem with very simple model class:
class Person
{
public long ID {get;set;}
public string Name { get; set;}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection) {
Person toUpdate = Repository.All<Person>().Single(p => p.ID == id);
TryUpdateModel(toUpdate, collection.ToValueProvider());
Repository.Update(toUpdate); //throws nullreferenceexception
return RedirectToAction("Index");
}
stack trace:
at SubSonic.Query.Update.GetCommand()
at SubSonic.Query.Update.Execute()
at SubSonic.Repository.SimpleRepository.Update[T](T item)
at MvcApplication1.Controllers.PersonController.Edit(Int32 id, FormCollection collection)
in H:\...\Controllers\PersonController.cs:line 71"
My configuration: SubSonic 3, SQLite, empty database
I ran into this problem as well and I was able to download the latest SubSonic source and the issue was already fixed. Just open the SubSonic.Core project and do a build and replace your project's reference to SubSonic.Core.
Download Latest Source
http://github.com/subsonic/SubSonic-3.0
Boom - Repository Update works again!

Resources