Hi
My question is that how can i use stored procedure in ef core 3.1 to return something like anonymous types without creating some viewModel as dbSet in our dbContext ?
Thanks in advance
Hi
My question is that how can i use stored procedure in ef core 3.1 to return something like anonymous types without creating some viewModel as dbSet in our dbContext ?
Thanks in advance
problem
I work on angular 7 app I click button to export data from database to Excel it create file when i open it
give me error ( excel file not readable content ) why and how to solve issue this my problem .
I pass parameter value to stored procedure and execute it and get result from database then export it to excel .
Exec exec dbo.getRevision 19253747
Main issue why not export data to excel and how to make export correct this actually what i need .
web API asp.net core 2.2
[HttpPost] public IActionResult GetDataBasedOnDynamicSp([FromBody] dynamic DataObjectRevision) { string SpName = DataObjectRevision[0].downLoadProcedureName; string revid = DataObjectRevision[0].revisionID; var PostRevision = _reportservice.GetSpByRevisionId(revid, SpName); return Ok(PostRevision); }
Angular service.ts
GetSpByRevisionId(datarevision : any){ return this.http.post<any>('http://localhost:61265/api/report',datarevision) }
component.ts
public exportJsonAsExcelFile(json: any[], excelFileName: string): void { const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json); const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] }; const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }); this.saveAsExcelFile(excelBuffer, excelFileName); } private saveAsExcelFile(buffer: any, fileName: string): void { const data: Blob = new Blob([buffer], { type: EXCEL_TYPE }); FileSaver.saveAs(data, fileName + new Date().getTime() + EXCEL_EXTENSION); } getDataByRevision(RevId : any) { this.ReportData.forEach(function(e) { e.revisionID=RevId }); this._displayreport.GetSpByRevisionId(this.ReportData).subscribe(data=>{ console.log(data) this.exportJsonAsExcelFile(this.ReportData ,'datarevision'); }); }
component .html
<td> <button (click)="getDataByRevision(rep[0])">Download</button> </td>
Data below is result of API and angular above and this data Exactly must show on Excel But this Not Done
(3) [{…}, {…}, {…}] 0: {revisionid: 19253747, revisionname: "parts", revisioncity: "usa"} 1: {revisionid: 19253747, revisionname: "company", revisioncity: "russia"} 2: {revisionid: 19253747, revisionname: "family", revisioncity: "german"} length: 3 __proto__: Array(0)
Hi
whats is the best setup and design pattern for holding and using configuration settings/string for things like databases, messaging services etc
i need to for multiple enviroments eg dev, staging production
this is for azure functions,but i don't think that makes any difference.
what i am usingnow is a mix and i don't like them.
Any suggestions welcome.
HI Team,
I am migrating asp.net project Unittest(UT )to asp.net core 3.1 and observed Fake dll not getting generated there
please suggest
</div>I'm using the following scaffolded example with angular and ASP.NET Identity with IdentityServer4.
dotnet new angular -o <output_directory_name>-au Individual
The implementation is amazing, because it uses the recommended code with PKCE with angular OIDC client, which I tried to do myself, but it's way more code and it doesn't look as good as Microsoft's.
I want to use angular login/register pages instead of the default MVC views. Is that possible? I'm aware that what they did is also a separate part of the project, but I still want to use angular views. My angular and ASP.NET Core projects are completely
separate and I don't use services.AddSpaStaticFiles
which optimizes angular and starts angular at same port with the ASP.NET Core.
I have the following asp.net core MVC6 web grid https://mvc6-grid.azurewebsites.net/ :-
@(Html .Grid(Model) .Build(columns => { columns.Add(model => model.PhysicianFirstName).Titled("Name"); columns.Add(model => model.PhysicianLastName).Titled("Surname"); columns.Add(model => model.Phone).Titled("Phone"); columns.Add(model => $" <a asp-action='Edit' asp-route-id=\"{model.Id}\">Edit</a> |<a asp-action='Details' asp-route-id=\"{model.Id}\">Details</a> |<a asp-action='Delete' asp-route-id=\"{model.Id}\">Delete</a>").Encoded(false); }) .Using(GridFilterMode.Header) .Empty("No data found") .Filterable() .Sortable() .Pageable(pager => { pager.RowsPerPage = 250; })
where inside the last column i specify to add 3 links (Edit,Details & Delete), where the links will be shown but they will be UN-clickable, so not sure why?
here is a screen shot of the results and the markup that got generated:-
Hi, I am creating an Asp net core 2.2 application for witch I need to update my database frequently. I used to do this with Migrations (add-Migration and update-Database ). But lately I get an error message when I try to use the Update-Database migration command, saying: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
My guess is that this has to do with the fact that I added a singleton Database reference in my Startup.cs file (see microsoft forum: https://forums.asp.net/t/2165973.aspx?Dependency+injection+in+HostedService+failing.
The database reference did not change and the 'normal' database access is still working without problems. I can workaround this problem by using an backup from before this implementation, and apply the migration on this backup. but things are getting rather messy this way.
My question : is this a known problem with migrations? if so what is the solution to fix it? if not a known problem, can somebody tell me where the update-database migration command gets its database reference from?
Hi All.
This is a typical question and would require knowledge of Vericred medicare API to some extent. Calling the API through .NET Core application. Already registered with the developers account and have relevant key stored in json file.
Here's the calling code:
[Route("GetMedicineData/med_name")] [HttpGet] public async Task<ActionResult<DrugsModel>> GetMedicineData(string med_name) { APIRequestMaker objAPI = new APIRequestMaker(_config); DrugsModel drugsModel = new DrugsModel(); string apivalue = _config.GetSection("Vericred:API_Key").ToString(); try { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("api.vericred.com")); *** this line client.DefaultRequestHeaders.Add("Authorization", "API Key" + apivalue); var streamTask = client.GetStreamAsync("api.vericred.com/drugs?search_term=" + med_name.ToString()); var drugData = await JsonSerializer.DeserializeAsync<DrugsModel>(await streamTask); return (drugData); } } catch(Exception exp) { throw exp.GetBaseException(); } }
Here DrugsModel is the corresponding mapped model
When you run it, the exception thrown on the line marked is The format of value 'api.vericred.com' is invalid.
Not sure why that pops up. Things look like I did more or less correctly. If you test via Postman, the API endpoint, you need to select API Key as 'Type' and provide Key-Value as Vericred-Api-Key - blablaablablaaawhatever.
Simply put I have tried to replicate that in my code. The official docs at Vericred Developer don't contain relevant instructions/guiline.
Thanks.
I would like to read the contents of several tables into a singleton so that I don't have to keep querying my database for (mostly) static data. When writing the routines to read the database, they all seemed the same so I created a generic method to do so. Works fine.
However, I am unable to assign the results of the table data generically to static members of the singleton. An illustration would probably help. Here's my Singleton class
public sealed class Tables // Sealed so nothing can inherit this class { private static Tables instance; private Tables() { } // Tables to read. Only want to get these once public static List<Linksmvccore> _alllinks { get; set; } = null; public static List<Peoplemvc> _allpeople { get; set; } = null; public static List<Bagsmvc> _allbags { get; set; } = null; public static List<Country> _allcountries { get; set; } = null; public static List<Country> _allpertinentcountries { get; set; } = null; //public static Dictionary<string, List<T> _alltables { get; set; } = //{ // {"Links", _alllinks } //} public static async Task<Tables> GetFromTable<T>(DbSet<T> TableToRead) where T : class { if (instance == null) { instance = new Tables(); } if (_alllinks == null) // _alllinks is not generic!!!! { var x = await TableToRead.ToListAsync(); _alllinks = x as List<Linksmvccore>; // List<Linksmvccore> is not generic!!!! } return instance; } }
Here is how I call the generic singleton method for the "Links" table
await Tables.GetFromTable(_context.Links);
I attempted to put everything in a static generic data dictionary with no success. I could also put a switch statement into GetFromTable() and load each list based upon typeof(T) but if I someday have hundreds of tables, this seems like a bad idea. Any help appreciated.
I got the following message below and have no idea what to do?
TypeLoadException: Method 'Create' in type 'Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitorFactory' from assembly 'Microsoft.EntityFrameworkCore.SqlServer, Version=3.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation.
Below is my code for ApplicationDbContext:
<div>using Bumples15.Models;Thanks Jen
Below is the error that I am getting in program cs. I am using aspnet core mvc 3.1
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole] Lifetime: Scoped ImplementationType:
Here is the program:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Bumples15
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run(); //here is where they say the problem is.
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Below is the startup page
using Bumples15.Models;
using Bumples15.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
namespace Bumples15
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddScoped<RoleManager<IdentityRole>>();
services.AddScoped<IRepository<Product>, SqlBooksRepository>();
services.AddScoped<IRepository<Order>, SqlOrdersRepository>();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
The course that I am using is a 2.1 program but I have tried to update it to 3.1. Where am I going wrong,
Thanks,
Jen
HomeController.Homecontroller(Irepository<Issue>issue)
Hi, I don't understand why I am getting this error. Below is part of the home controller that I am using. I have tried everything. I am using aspnetcore mvc 3.1.
using System;
using System.Collections.Generic; (is not in dark print)
using System.Linq;
using System.Threading.Tasks; (is not in dark print)
using Bumples15.Models;
using Bumples15.Services;
using Bumples15.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering; (is not in dark print)
namespace Bumples15.Controllers
{
public class HomeController : Controller
{
private readonly IRepository<Issue> _issueRepo;
public HomeController(IRepository<Issue> issue)
{
_issueRepo = issue;
}
Thanks, Jen
I want to write an word press plugin whit asp.net in order to add sum special services that are not support by ordinary plugin .
<div id="skyroom-extension-is-installed"></div>Hello,
I develop a quiz application. In my database design, there is many-to-many relationship between Test takers and questions as same exam questions may concern various test takers and each test taker will have many questions of the same exam. My problem is that I cannot write right action in controller so that when each user submit their answer while they are logged in, and if it's true, the relevant question score for each user must be saved in database. So, considering this, my model is like this:
Question
public class Question { public Question() { Answers = new HashSet<Answer>(); } public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public Exam Exam { get; set; } public int ExamId { get; set; } public TimeSpan? Remainedtime { get; set; } public int Score { get; set; } public ICollection<Answer> Answers { get; set; } public ICollection<UserQuestion> UserQuestions { get; set; } }
ExamUser
public class ExamUser: IdentityUser { public TestTaker TestTaker { get; set; } public int? TestTakerId { get; set; } }
TestTaker
public class TestTaker { public int Id { get; set; } [Required] public string Name { get; set; } public string Phone { get; set; } public string Education { get; set; } public string Job { get; set; } public DateTime Birth { get; set; } public ExamUser ExamUser { get; set; } public int Result { get; set; } public ICollection<UserQuestion> UserQuestions { get; set; } }
UserQuestion (moderate table for many-to-many relationship)
public class UserQuestion { public int TestTakerId { get; set; } public TestTaker TestTaker { get; set; } public int QuestionId { get; set; } public Question Question { get; set; } }
The reason why I didn't connect ExamUser directly to questions is that its built in Id is string (it might cause problem while inserting to database).
In DbContext
public class IntellectDbContext:IdentityDbContext<ExamUser> { public IntellectDbContext(DbContextOptions<IntellectDbContext> dbContextOptions) : base(dbContextOptions) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<UserQuestion>() .HasKey(a => new { a.TestTakerId, a.QuestionId }); modelBuilder.Entity<UserQuestion>() .HasOne(a => a.TestTaker) .WithMany(b => b.UserQuestions) .HasForeignKey(a => a.TestTakerId); modelBuilder.Entity<UserQuestion>() .HasOne(a => a.Question) .WithMany(c => c.UserQuestions) .HasForeignKey(a => a.QuestionId); } public DbSet<Answer> Answers { get; set; } public DbSet<Question> Questions { get; set; } public DbSet<Exam> Exams { get; set; } public DbSet<ExamUser> ExamUsers { get; set; } public DbSet<UserQuestion> UserQuestions { get; set; } public DbSet<TestTaker> TestTakers { get; set; } }
View
@model Intellect.Models.ViewModels.AdminViewModel @{ Layout = "AdminLayout"; }<div class="questioncontainer"> <form asp-action="Question" asp-controller="Home" asp-route-id="@Model.NextQuestion.Id" asp-route-count="@ViewBag.Equestions"><div class="row"><div class="col-lg-3"></div><div class="col-lg-6 col-sm-12"><table><tr><th>Qaliq vaxt</th></tr><tr><td><input asp-for="Question.Score" id="time" name="timer" /></td></tr></table><div class="question">@Model.CurrentQuestion.Description </div></div><div class="col-lg-3"></div></div><div class="row"><div class="col-lg-3 col-sm-12"> @foreach (Answer item in Model.Answers) {<input asp-for="@item.Id" name="@item.Id" hidden /><input type="radio" asp-for="@item.Id" name="myanswer" value="@item.Id" />@item.Description<br> }</div><div class="col-lg-3"></div></div><div class="row"><div class="col-lg-6 col-sm-4"></div><div class="col-lg-3 col-sm-4"></div><div class="col-lg-3 col-sm-4"><div class="nextbtn"> @if (ViewBag.Equestions == 0) {<input type="submit" value="Finish" /> } else {<input type="submit" value="Next" /> }</div></div></div></form></div> @section Script{ <script> function StartTimer(seconds) { var intSeconds = seconds; var timer = setInterval(myTimer, 1000); function myTimer() { if (intSeconds < 0) { Alert("bitdi") clearInterval(timer) return; } document.getElementById("time").value = intSeconds; intSeconds--; } } StartTimer(60);</script> }
Here is the Controller where error lies
public class HomeController : Controller
{
private readonly IntellectDbContext _intellectDbContext;
private readonly UserManager<ExamUser> _userManager;
private readonly SignInManager<ExamUser> _signInManager;
static int exam_id = 0;
static int? PreviousId = 0;
static int result = 0;
static int correctAnswer = 0;
static List<Question> RemainedQuestions = new List<Question>();
static List<int> trueAnswers = new List<int>();
public HomeController(IntellectDbContext intellectDbContext, UserManager<ExamUser> userManager, SignInManager<ExamUser> signInManager)
{
_intellectDbContext = intellectDbContext;
_userManager = userManager;
_signInManager = signInManager;
}
[HttpGet]
public async Task<IActionResult> Test(int Id)
{
exam_id = Id;
AdminViewModel admodel = new AdminViewModel();
admodel.Equestions = await _intellectDbContext.Questions.Include(q => q.Answers).Where(q => q.ExamId == Id).ToListAsync();
admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(q => q.ExamId == Id).FirstOrDefaultAsync();
RemainedQuestions = admodel.Equestions;
PreviousId = admodel.CurrentQuestion.Id;
return View(admodel);
}
[HttpGet]
public async Task<IActionResult> Question(int Id, int count)
{
AdminViewModel admodel = new AdminViewModel();
admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(x => x.Id == Id).SingleOrDefaultAsync();
admodel.Answers = await _intellectDbContext.Answers.Where(y => y.QuestionId == Id).ToListAsync();
admodel.Equestions = await _intellectDbContext.Questions.Where(q => q.ExamId == exam_id).ToListAsync();
if (count > 1)
{
var question = RemainedQuestions.Single(r => r.Id == admodel.CurrentQuestion.Id);
PreviousId = question.Id;
RemainedQuestions.Remove(question);
admodel.NextQuestion = RemainedQuestions[0];
count -= 1;
}
else
{
admodel.NextQuestion = RemainedQuestions[0];
count -= 1;
}
if (count == -1)
{
return RedirectToAction(nameof(Finish));
}
ViewBag.Equestions = count;
return View(admodel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Question(int Id, int count, int myanswer, int timer)
{
AdminViewModel admodel = new AdminViewModel();
admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(x => x.Id == Id).SingleOrDefaultAsync();
admodel.Answers = await _intellectDbContext.Answers.Where(y => y.QuestionId == Id).ToListAsync();
admodel.Equestions = await _intellectDbContext.Questions.Where(q => q.ExamId == exam_id).ToListAsync();
correctAnswer = _intellectDbContext.Answers.Where(a => a.QuestionId == PreviousId && a.Correct == true).SingleOrDefault().Id;
if (_signInManager.IsSignedIn(User))
{
ExamUser examTaker = await _userManager.GetUserAsync(HttpContext.User);
examTaker.TestTaker = await _intellectDbContext.TestTakers.FirstOrDefaultAsync();
admodel.CurrentQuestion = await _intellectDbContext.Questions.Include(q => q.UserQuestions).Where(u => u.Id == Id).SingleOrDefaultAsync();
if (myanswer == correctAnswer)
{
admodel.CurrentQuestion.Score = timer;
await _intellectDbContext.SaveChangesAsync();
// admodel.CurrentQuestion.Score = result;
}
}
if (count > 1)
{
var question = RemainedQuestions.Single(r => r.Id == admodel.CurrentQuestion.Id);
PreviousId = question.Id;
RemainedQuestions.Remove(question);
admodel.NextQuestion = RemainedQuestions[0];
count -= 1;
}
else
{
admodel.NextQuestion = RemainedQuestions[0];
count -= 1;
}
if(count == -1)
{
return RedirectToAction(nameof(Finish));
}
ViewBag.Equestions = count;
return RedirectToAction(nameof(Question));
}
I need to write right LINQ in highlighted code so that admodel.currentQuestion would give me the question with that Id that concerns TestTaker which is logged in (whose Id is say 10). So, after running the application, when clicking on Next button to go the following question, SQL Exception rises: https://prnt.sc/selfav
Of course, when testTaker enrolls for the exam, userQuestions table is fillied for its Id with that exam's question Ids.
[HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Enroll(TestTaker testTaker, DateTime birthdate) { if (ModelState.IsValid) { testTaker.Birth = birthdate; testTaker.Result = 0; testTaker.UserQuestions = await _intellectDbContext.Questions.Where(q => q.ExamId == 3).Select(q => new UserQuestion { Question = q, TestTaker = testTaker }).ToListAsync(); _intellectDbContext.TestTakers.Add(testTaker); await _intellectDbContext.SaveChangesAsync(); return RedirectToAction(nameof(Proceed)); } else { ModelState.AddModelError("", "Kecmedi"); return View(); } }
It's like it sees that I'm trying to insert testTaker again to database while I need to set admodel.currentQuestion to that testTaker's Id so that its score would calculated for the TestTaker with id say 10. Also, this solutiuon must work when several test takers take exam, like you know from Trivia game.
I am trying to list the record from JS datatable . My html is given below
@model LibraryBooks.Models.ViewModels.CategoryVM @{ Layout = "~/Views/Shared/_Layout.cshtml"; }<table id="tblData" class="table table-striped table-bordered" style="width:100%"><thead class="thead-dark"><tr class="table-info"><th>CategoryName</th><th></th></tr></thead><tbody></tbody></table> @section Scripts{ <script src="~/js/Category.js"></script> }
Category.js
Category.js var dataTable; $(document).ready(function () { loadDataTable(); }); function loadDataTable() { dataTable = $('#tblData').DataTable({"ajax": {"url": "/Admin/Category/GetAll" },"columns": [ { "data": "CategoryName", "width": "60%" }, {"data": "id","render": function (data) { return `<div class="text-center"><a href="/Admin/Category/Upsert/${data}" class="btn btn-success text-white" style="cursor:pointer"><i class="fas fa-edit"></i> </a><a onclick=Delete("/Admin/Category/Delete/${data}") class="btn btn-danger text-white" style="cursor:pointer"><i class="fas fa-trash-alt"></i> </a></div> `; }, "width": "40%" } ] }); }
Model class
using LibraryBooks.Models; using System; using System.Collections.Generic; using System.Text; namespace LibraryBooks.Models.ViewModels { public class CategoryVM { public IEnumerable<Category> Categories { get; set; } public PagingInfo PagingInfo { get; set; } } } Category mdeols namespace LibraryBooks.Models { public class Category { [Key] public int Id { get; set; } [Display(Name="Category Name")] [Required] [MaxLength(50)] public string CategoryName { get; set; } } }
Controller
public IActionResult Index() { return View(); } [HttpGet] public IActionResult GetAll() { var allObj = _unitOfWork.Category.GetAll(); // The record is coming here but in data table it shows Requested unknown parameter 'CategoryName' return Json(new { data = allObj }); }
Please help , The column of the model is not being taken in html
Greetings,
I have created my first .NET Core Web API that will be sent to another site to be installed. I've searched the web but I cannot find any definitive guidelines and steps to properly package the Web API into an installer that can be given to the other
site to use to install it on their system.
Most articles assume the Web API was developed at the same location as the web server so they go into detail on how to publish to it. I have found very little valid information for actually packaging a web API and installing/publishing it using
the installer created.
Can someone please provide information on how to properly package an ASP .NET Core Web API so it can be installed at another site? It can be either instructions for MSI or MSIX. I created the Web API using ASP .NET Core 2.1 and Visual Studio 2017.
Thanks
Hi,
I am working on a project where i have to read an xml file.
But I have a problem.
<?xml version="1.0" encoding="utf-8" ?><products><product><id>100</id><name>Ball</name><price>15</price><quantity>2</quantity><description><comment>aaa</comment></description></product></products>
This is an example of the file that I have to import and read.
I can read id, name, price and quantity. I cant read description.
Bellow i will show my code in c#.
private List<Product> ProcessImport(string path) { XDocument xDocument = XDocument.Load(path); List<Product> products = xDocument.Descendants("product").Select (p => new Product() { Id = Convert.ToInt32(p.Element("id").Value), Name=p.Element("name").Value, Quantity = Convert.ToInt32(p.Element("quantity").Value), Price = Convert.ToDecimal(p.Element("price").Value), }).ToList(); foreach(var product in products) { var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id)); if(productInfo != null) { productInfo.Id = product.Id; productInfo.Name = product.Name; productInfo.Quantity = product.Quantity; productInfo.Price = product.Price; } else { db.Products.Add(product); } db.SaveChanges(); } return products; }
Do I have to do anything different?
Can you help me!?!?!?
Thanks!!
Hi
I have some fields in my model which do not need to display or edit via end user, It's system fields (such as CreatedBy, DateCreated, TimeCreated, LastModifiedBy, LastModifiedDate and LastModifiedTime) & controlled via my webApp (through overriding SaveChanges method).
This process works as well in Create action, but after Update action, those fields set to null.
Here is my Edit action :
[Route("Visit/Edit/{id?}")] public IActionResult Edit(string id) { var curVisitHeader = _dbContext.VisitHeaders.Find(Guid.Parse(id)); var patient = _dbContext.Patients.Find(curVisitHeader.PatientRowID); ViewBag.DiagnosisID = new SelectList(_dbContext.Diagnoses, "DiagnosisID", "DiagnosisName"); ViewBag.PatientFullName = string.Format("{0} {1}", patient.PatientFname, patient.PatientLname); return View("Edit", curVisitHeader); }
Here is my Edit view :
<form id="frmEditVisitItem" asp-action="Update" method="post"><div asp-validation-summary="All" class="text-danger"></div><input type="hidden" asp-for="VisitHeaderRowID" value="@Model.VisitHeaderRowID" /><input type="hidden" asp-for="PatientRowID" value="@Model.PatientRowID" /><input type="hidden" asp-for="ProductSupplierID" value="@Model.ProductSupplierID" /><input type="hidden" asp-for="MedicalCenterDoctorRowID" value="@Model.MedicalCenterDoctorRowID" /><input type="hidden" asp-for="OwnerTableName" value="@Model.OwnerTableName" /><input type="hidden" asp-for="OwnerID" value="@Model.OwnerID" /><div class="form-group"><label asp-for="VisitDate" class="control-label"></label><input asp-for="VisitDate" class="form-control" value="@Model.VisitDate" /><span asp-validation-for="VisitDate" class="text-danger"></span></div><div class="form-group"><label asp-for="Description" class="control-label"></label><textarea asp-for="Description" class="form-control" value="@Model.Description"></textarea><span asp-validation-for="Description" class="text-danger"></span></div><div class="form-group"><label asp-for="DiagnosisID" class="control-label"></label><select asp-for="DiagnosisID" class="form-control" asp-items="@ViewBag.DiagnosisID" value="@Model.DiagnosisID"></select><span asp-validation-for="DiagnosisID" class="text-danger"></span></div><div class="text-right"><button type="submit" id="btnCreateVisit" class="btn btn-success">Save</button> @Html.ActionLink("Back", "Details", "Patient", new { id = Model.PatientRowID })</div></form>
And here is my Update action :
[HttpPost] [ValidateAntiForgeryToken] public IActionResult Update([Bind("VisitHeaderRowID, PatientRowID, ProductSupplierID, VisitDate, Description, MedicalCenterDoctorRowID, DiagnosisID, OwnerTableName, OwnerID")] VisitHeaders visitHeader) { if (this.ModelState.IsValid) { _dbContext.Entry(visitHeader).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _dbContext.SaveChanges(); return RedirectToAction("Details", "Patient", new { id = visitHeader.PatientRowID }); } return View("Edit", visitHeader); }
How to work-around this problem?
Thanks in advance
I keep going from appplicationdbcontext file to program files errors.
Below is the error message I am using aspnet core mvc 3.1
System.TypeLoadException: 'Method 'Create' in type 'Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitorFactory' from assembly 'Microsoft.EntityFrameworkCore.SqlServer, Version=3.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation.'
Here is the ApplicationDBContext file
using Bumples15.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Bumples15.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) //here is the error
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
}
}
Below is the program file;
namespace Bumples15
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
here is the startup file:
using Bumples15.Data;
using Bumples15.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Bumples15
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddScoped<RoleManager<IdentityRole>>();
services.AddScoped<IRepository<Product>, SqlBooksRepository>();
services.AddScoped<IRepository<Order>, SqlOrdersRepository>();
services.AddRazorPages();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
Some of the programs were files taken from aspnet core mvc 2.1. But I think that I have upgraded them all.
Is that where my problem is:
Thanks
Jen
I have seen migration steps for .Net Framework to .Net Core at https://docs.microsoft.com/en-us/dotnet/core/porting/
Do anyone have other approach for Web API migration from .Net Framework 4.5 to .Net Core 3.0
Thanks in advance!!