Execute Sql query in entity framework - asp.net-mvc

I have a jquery data table in which i want to show a summarise report generated from sql query, but i am not able to do it, it shows error in the query. The summarise report consist of all month name and number of entries in every month.
Error:
System.Data.Entity.Core.EntityCommandExecutionException: 'The data reader is incompatible with the specified 'DHIFeedbackModel.FeedBack'. A member of the type, 'FeedbackUserName', does not have a corresponding column in the data reader with the same name.'
public ActionResult LoadData()
{
using (DHIFeedbackEntities2 Ms = new DHIFeedbackEntities2())
{
//var summary = Ms.FeedBacks.SqlQuery("select * from [DHIFeedback].[dbo].[FeedBack]").ToList<FeedBack>();
var summary = Ms.FeedBacks.SqlQuery(
#"SELECT *
FROM
(
SELECT
YEAR([FeedBackDate])[Year],DATENAME(MONTH, [FeedBackDate])[Month],
COUNT(1)[FeedbackID]
FROM
[DHIFeedback].[dbo].[FeedBack]
GROUP BY
YEAR([FeedBackDate]
),
DATENAME(MONTH, [FeedBackDate])) AS Monthlyupdate
PIVOT(SUM([FeedbackID]) FOR Month IN([January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December])) AS MNamePivot
order by 1,2"
).FirstOrDefault<FeedBack>();
return Json(new { data = summary }, JsonRequestBehavior.AllowGet);
}
}
and the javascript:
$(document).ready(function () {
$('#Summary').DataTable({
"processing": true,
"ajax": {
"url": "/Summary/LoadData",
"type": "GET",
"datatype": "json",
},
"lengthMenu": [
[5, 10, 25, 50, 100, -1],
[5, 10, 25, 50, 100, "All"]
],
"autoWidth": true,
"responsive": true,
"lengthChange": true,
"ordering": true,
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
var oSettings = this.fnSettings();
$("td:first", nRow).html(oSettings._iDisplayStart + iDisplayIndex + 1);
return nRow;
},
"columns": [
{ "data":"Year", "autoWidth": true },
{ "data":"January", "autoWidth": true },
{ "data":"February", "autoWidth": true },
{ "data":"March", "autoWidth": true },
{ "data":"April", "autoWidth": true },
{ "data":"May", "autoWidth": true },
{ "data":"June", "autoWidth": true },
{ "data":"July", "autoWidth": true },
{ "data":"August", "autoWidth": true },
{ "data":"September", "autoWidth": true },
{ "data":"October", "autoWidth": true },
{ "data":"November", "autoWidth": true },
{ "data":"December", "autoWidth": true }
]
});
});
public partial class FeedBack
{
public int FeedbackID { get; set; }
public string FeedbackUserName { get; set; }
public string FeedBackUserEmailID { get; set; }
public string FeedBackComment { get; set; }
public string Designation { get; set; }
public string Organization { get; set; }
public string ContactNo { get; set; }
public string City { get; set; }
public Nullable<System.DateTime> FeedBackDate { get; set; }
public Nullable<double> IsPublished { get; set; }
public string Reply { get; set; }
public Nullable<double> IsReplied { get; set; }
public Nullable<System.DateTime> ReplyDate { get; set; }
public string ReplyBy { get; set; }
public string Sector { get; set; }
public Nullable<int> Status { get; set; }
public int Year { get; set; }
public int January { get; set; }
public int February { get; set; }
public int March { get; set; }
public int April { get; set; }
public int May { get; set; }
public int June { get; set; }
public int July { get; set; }
public int August { get; set; }
public int September { get; set; }
public int October { get; set; }
public int November { get; set; }
public int December { get; set; }
public string Monthlyupdate { get; set; }
public string Month{ get; set; }
[NotMapped]
public List<FeedBack> FeedBackCollection { get; set; }

the error means that the ORM is expecting a resultset comprising each and every property of FeedBacks including the one named FeedbackUserName
So you need to edit the select clause of your sql to return all the expected columns.
or you may use
Ms.Database.SqlQuery<SomeType>(
"your query here").ToList();
where SomeType is :
public class SomeType {
public int Year {get; set;}
//... and/or all the pivoted columns
}

Related

.NET Core 5.0 EF Migration add new foreign column

I have an application with .net core Entity Framework code first.
I have 2 tables in relationships.
altKategori and anaKategori
altKategoris
public class altKategori
{
[Key]
public int idAltKategori { get; set; }
[Column(TypeName = "Varchar")]
[StringLength(30)]
public string adAltKategori { get; set; }
public int idAnaKategori { get; set; }
public anaKategori anaKategori { get; set; }
}
anaKategoris
public class anaKategori
{
[Key]
public int idAnaKategori { get; set; }
[Column(TypeName = "Varchar")]
[StringLength(30)]
public string adAnaKategori { get; set; }
public List<altKategori> altKategoris { get; set; }
}
Also there is my Context:
public class Context : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server=.\\MSSQLSERVER2019;database=deneme;User ID=deneme1;Password=****;");
}
public DbSet<altKategori> altKategoris { get; set; }
public DbSet<anaKategori> anaKategoris { get; set; }
}
When I start migration, migration automatic add anaKategoriidAnaKategori columns, and add relationship with that column.
migrationBuilder.CreateTable(
name: "altKategoris",
columns: table => new
{
idAltKategori = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
adAltKategori = table.Column<string>(type: "Varchar(30)", maxLength: 30, nullable: true),
idAnaKategori = table.Column<int>(type: "int", nullable: false),
anaKategoriidAnaKategori = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_altKategoris", x => x.idAltKategori);
table.ForeignKey(
name: "FK_altKategoris_anaKategoris_anaKategoriidAnaKategori",
column: x => x.anaKategoriidAnaKategori,
principalTable: "anaKategoris",
principalColumn: "idAnaKategori",
onDelete: ReferentialAction.Restrict);
});
I don't want to relation with anaKategoriidAnaKategori. I want to relation with idAnaKategori. How can I?
Thanks for your help.
try to add relation attributes
public class altKategori
{
[Key]
public int idAltKategori { get; set; }
[Column(TypeName = "Varchar")]
[StringLength(30)]
public string adAltKategori { get; set; }
public int idAnaKategori { get; set; }
[ForeignKey(nameof(idAnaKategori ))]
[InverseProperty("altKategoris")]
public anaKategori anaKategori { get; set; }
}
public class anaKategori
{
[Key]
public int idAnaKategori { get; set; }
[Column(TypeName = "Varchar")]
[StringLength(30)]
public string adAnaKategori { get; set; }
[InverseProperty(nameof(altKategori.anaKategori))]
public List<altKategori> altKategoris { get; set; }
}

Get method returns Nulls when using Include on EF

I have the following get method which returns out of stock items in my database. My database is broken up into 2 tables, one called stock and one called Issue. My stock table is joined on the issue table (Both of them have IssueId in them)
When i run the following code:
public IEnumerable<Stock> GetOutOfStock(int page)
{
var stock = (from s in _context.Set<Stock>().Cast<Stock>()
where s.AvailableQty == 0
orderby s.Issue.PublicationDate descending
select s).Skip(25 * page).Take(25);
//.Include(s => s.Issue)
return stock;
}
I get this as my output:
{
"stockReferenceId": 32681,
"issueId": 7980,
"condition": "Fine",
"availableQty": 0,
"price": 51.94,
"comments": null,
"issue": null,
"supplierOrders": [],
"supplierQuotes": []
}
but as soon as i Include my Issue table with the following code:
public IEnumerable<Stock> GetOutOfStock(int page)
{
var stock = (from s in _context.Set<Stock>().Cast<Stock>()
where s.AvailableQty == 0
orderby s.Issue.PublicationDate descending
select s).Include(s => s.Issue).Skip(25 * page).Take(25);
//
return stock;
}
I get the following output
{
"StockReferenceId": 0,
"IssueId": 0,
"Condition": "string",
"AvailableQty": 0,
"Price": 0,
"Comments": "string",
"Issue": {
"IssueId": 0,
"Title": "string",
"PublicationDate": "2020-02-17T08:55:27.501Z",
"Publisher": "string",
"SeriesNumber": 0,
"Description": "string",
"CoverImage": "string",
"ComicCreators": [
{
"IssueId": 0,
"CreatorId": 0,
"CreatorRole": "string",
"Creator": {
"CreatorId": 0,
"Name": "string",
"CountryOfResidence": "string",
"TaxReferenceNumber": "string",
"EmailAddress": "string",
"ComicCreators": [
null
]
}
}
My domain tables look like this:
Stock:
public Stock()
{
//Cart = new HashSet<Cart>();
//OrderDetails = new HashSet<OrderDetails>();
SupplierOrders = new HashSet<SupplierOrders>();
SupplierQuotes = new HashSet<SupplierQuotes>();
}
public int StockReferenceId { get; set; }
public int? IssueId { get; set; }
public string Condition { get; set; }
public short? AvailableQty { get; set; }
public decimal? Price { get; set; }
public string Comments { get; set; }
public Issues Issue { get; set; }
and my Issue table looks like this:
public partial class Issues
{
public Issues()
{
ComicCreators = new HashSet<ComicCreators>();
Stock = new HashSet<Stock>();
}
public int IssueId { get; set; }
public string Title { get; set; }
public DateTime? PublicationDate { get; set; }
public string Publisher { get; set; }
public short? SeriesNumber { get; set; }
public string Description { get; set; }
public string CoverImage { get; set; }
public ICollection<ComicCreators> ComicCreators { get; set; }
public ICollection<Stock> Stock { get; set; }
}
How do i get my get request to return my stock and Issue in my Json?

Assign value to child object and handle list object values

First please start from picture i have attached the json output view. On picture you will see i was able to assign value only to the root level objects but on child level i failed to assign value properly which i need. My main goal is get output exactly like Json code bellow. How can i fix my controller to get exactly example json type output from JavaScriptSerializer?
Controller:
var root = new RootObject();
root.name = "Jan Kowalski";
root.email = "jan.kowalski#wp.pl";
root.dayOfCycle = "10";
//root.tags.Add(new Tag
//{
// tagId = "Xw",
//});
//root.scoring = 25;
//root.customFieldValues.Add(new CustomFieldValue
//{
// customFieldId = "n",
// //value = "white", value should be list
//});
root.ipAddress = "89.206.36.193";
var camp = new Campaign();
camp.campaignId = "jf7e3jn";
var jsBody = new JavaScriptSerializer().Serialize(root);
Model class:
public class Campaign
{
public string campaignId { get; set; }
}
public class Tag
{
public string tagId { get; set; }
}
public class CustomFieldValue
{
public string customFieldId { get; set; }
public List<string> value { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string email { get; set; }
public string dayOfCycle { get; set; }
public Campaign campaign { get; set; }
public List<Tag> tags { get; set; }
public int scoring { get; set; }
public List<CustomFieldValue> customFieldValues { get; set; }
public string ipAddress { get; set; }
}
Json body i want from JavaScriptSerializer:
{
"name": "Jan Kowalski",
"email": "jan.kowalski#wp.pl",
"dayOfCycle": "10",
"campaign": {
"campaignId": "jf7e3jn"
},
"tags": [
{
"tagId": "Xw"
},
{
"tagId": "Nn"
}
],
"scoring": 25,
"customFieldValues": [
{
"customFieldId": "n",
"value": [
"white"
]
}
],
"ipAddress": "89.206.36.193"
}
As commented already, for the sake of completeness:
Missing: root.campaign = camp; just before creation of jsBody
Missing root.tags = new List<Tag>(); to prevent Null Reference Exception, just before root.tags.Add is executed

How to access a List objects in an ASP.Net web service

I am new in ASP.Net and MVC5 programming,in fact I have a problem,I have this Class "Student":
namespace Project.Entities.Models
{
public partial class Student : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
[ForeignKey("ClassId")]
public virtual Class Class { get; set; }
public Int64 ClassId { get; set; }
[ForeignKey("ImageId")]
public virtual Image Image { get; set; }
public Int64 ImageId { get; set; }
public virtual List<Mark> Marks { get; set; }
public virtual List<Punishment> Punishments { get; set; }
public Student()
{
Marks = new List<Mark>();
Punishments = new List<Punishment>();
}
}
Class "Mark":
namespace SMA.Entities.Models
{
public partial class Mark : BaseEntity
{
public int Score { get; set; }
public string Note { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; }
public Int64 StudentId { get; set; }
}
}
I want to get the Marks of each Student,but I don't know How,
this is what I get in JSON result:
[
{
FirstName: "Student ",
LastName: "1",
Class: null,
ClassId: 1,
Image: null,
ImageId: 1,
Marks: [ ],
Punishments: [ ],
Id: 1,
ObjectState: 0
},
{
FirstName: "Student ",
LastName: "2",
Class: null,
ClassId: 2,
Image: null,
ImageId: 2,
Marks: [ ],
Punishments: [ ],
Id: 2,
ObjectState: 0
}
]
so please,have you any idea about,how can I access the Marks data for each Student
thanks for help
Assuming that you have an Id field in your Student entity that is the primary key (you didn't show it in the question, but I assume it was omitted), try changing this:
public virtual List<Mark> Marks { get; set; }
public virtual List<Punishment> Punishments { get; set; }
to
public virtual ICollection<Mark> Marks { get; set; }
public virtual ICollection<Punishment> Punishments { get; set; }

navigation properties not saving

I have a simple object model
public class License
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string CreationUserId { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string LastModifiedUserId { get; set; }
public string LicenseName { get; set; }
public LicenseType LicenseType { get; set; }
public State State { get; set; }
public DateTime DateIssued { get; set; }
public int ValidFor { get; set; }
}
public class State
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string CreationUserId { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string LastModifiedUserId { get; set; }
[StringLength(2)]
[Required]
public string Name { get; set; }
[Display(Name = "Long Name")]
[Required, StringLength(25)]
public string LongName { get; set; }
}
public class LicenseType
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string CreationUserId { get; set; }
[ScaffoldColumn(false), StringLength(20)]
public string LastModifiedUserId { get; set; }
[StringLength(100), Required]
public string Description { get; set; }
}
I am using the hot towel template breeze, durandal, knockout.
I have a simple add view model
var _licenseAdded = false;
var vm = {
states: ko.observableArray(context.states),
licenseTypes: ko.observableArray(context.licenseTypes),
viewAttached: function () {
var self = this;
$('input[name^="date"]').datepicker();
$('#validFor').spinner({
min: 365,
max: 3650,
step: 30
});
log('add Attached', null, true);
},
activate: function () {
var self = this;
self.original = context.manager.createEntity('License', { licenseName: 'Testing321', dateIssued: moment().format('L') }, null);
log('add Activated', null, true);
},
canDeactivate: function () {
if (_licenseAdded === false) {
return app.showMessage('Are you sure you want to leave this page?', 'Navigate', ['Yes', 'No']);
} else {
return true;
}
},
saveChanges: function () {
$.when(context.saveNewLicense()).done(function () {
_licenseAdded = true;
});
router.navigateTo('home');
},
original: undefined
};
return vm;
And here is my add.html, everything binds up fine and works beautifully until saving.
When I call saveChanges the saveBundle sent to the controller has no navigation properties attached that allow for the correct State and LicenseType to be stored I only get:
saveBundle {
"entities": [
{
"Id": -1,
"CreationUserId": null,
"LastModifiedUserId": null,
"LicenseName": "new for testing",
"DateIssued": "2013-03-11T04:00:00Z",
"ValidFor": 0,
"entityAspect": {
"entityTypeName": "License:#Volt.Telecom.Licensing.Models",
"entityState": "Added",
"originalValuesMap": {},
"autoGeneratedKey": {
"propertyName": "Id",
"autoGeneratedKeyType": "Identity"
}
}
}
],
"saveOptions": {
"allowConcurrentSaves": false
}
}
Don't think I can get much more vanilla than this. Why might this occur? When I am debugging on the client the state and licenseType navigationProperties are all correct and with the correct values.
I think the issue is that your EF model uses 'Independent Associations' instead of 'Foreign Key Assocations' (foreign key associations are the EF default). We do need to do a better job of documenting this assumption.
The reason for this requirement, which can be bypassed but with a substantial loss of functionality, is that the existence of foreign keys on the client is what allows breeze to automatically fix up relationships between entities that might be queried separately.
See the following MSDN article for more background: foreign-keys-in-the-entity-framework

Resources