Save data to firebase realtime from a picker's item which data is retrieved from firebase also, in xamarin form - firebase-realtime-database

My problem is how to save data from picker's value to firebase realtime. Anyway, Im super beginner to xamarin and so far I cant find any solution to my problem.
This is what I tried.
//my model
`
public int DeliveryPrice { get; set; }
public int PickUp_Price { get; set; }
public string gallonType { get; set; }
public string refillName { get; set; }
public int refill_id { get; set; }
public string waterType { get; set; }
`
//Code how I get the data from my firebase realtime db
`
public async Task<List<PRODUCT_REFILL>> GetAllProductRefill()
{
return
(await firebaseClient.Child
(nameof(PRODUCT_REFILL))
.OnceAsync<PRODUCT_REFILL>()).Select(item => new PRODUCT_REFILL
{
DeliveryPrice=item.Object.DeliveryPrice,
PickUp_Price=item.Object.PickUp_Price,
gallonType=item.Object.gallonType,
refillName=item.Object.refillName,
waterType=item.Object.waterType,
refill_id=item.Object.refill_id
}).ToList();
}
`
//my picker design UI
`
<Picker x:Name="Picker_ProductType"
ItemsSource="{Binding refillName}"
ItemDisplayBinding="{Binding refillName}">
<Picker.Items > <x:String >
</x:String>
<x:String>
</x:String>
</Picker.Items>
</Picker>
`
//my codebehind
`
Product_RefillRepo productrefill = new Product_RefillRepo();
async protected override void OnAppearing()
{
var productRefill = await productrefill.GetAllProductRefill();
Picker_ProductType.ItemsSource = productRefill;
}
`
//in my order button, which is also inside in code behind.cs
string orderProductType = Picker_ProductType.SelectedItem.ToString();
Then if click the order button, I got this error.
Edit; This is the error----- Error says; System.InvalidCastException: 'Specified cast is not valid.'
any link that will be commented that are related to my post, will highly appreciated, Thank you so much.

Related

Syncfusion Server-Side event is not passing data

I have a Asp.Net MVC project created from Syncfusion ASP.New MVC (Essential JS 2) VS template that is using Syncfusion's Data Grid. I can get the CrudUpdate event set in CrudUrl to fire at the server, however the value returned to CrudUpdate is empty. action parameter seems correctly set.
If I cast the value as Object, I get back a not-null, but VS cannot interrogate it. My guess is some weirdness in the way the value is cast or returned.
Has anyone got a complete working sample of the Syncfusion grid using the CrudUrl method with MVC (not asp). I am also guessing I may have some dependency issue.
View
#Html.EJS().Grid("CrudUrl").DataSource(dataManager => { dataManager.Url("/TestGrid2/UrlDatasource").CrudUrl("/TestGrid2/CrudUpdate").Adaptor("UrlAdaptor"); }).Columns(col =>
{
col.Field("RowKey").IsPrimaryKey(true).Add();
col.Field("PartitionKey").Add();
col.Field("sourceResourceId").Add();
col.Field("imagesLocation").Add();
col.Field("imagesResourceGroup").Add();
col.Field("imagePrefix").Add();
col.Field("imageVersion").Add();
}).AllowPaging().Toolbar(new List<string>() { "Search", "Add", "Edit", "Delete", "Update", "Cancel" }).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true); }).Render()
Controller
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Script.Services;
using System.Web.Services;
using DB;
//using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Base;
namespace VMSSManagmentConsole.Controllers
{
public class TestGrid2Controller : Controller
{
private ModelContainer db = new ModelContainer();
public ActionResult TestGrid2()
{
//var items = db.ManagementItems.ToList();
//ViewBag.dataSource = items;
return View();
}
public ActionResult UrlDatasource([FromBody]DataManagerRequest dm)
{
IEnumerable DataSource = db.ManagementItems.ToList();
DataOperations operation = new DataOperations();
int count = DataSource.Cast<ManagementItem>().Count();
if (dm.Skip != 0)
{
DataSource = operation.PerformSkip(DataSource, dm.Skip); //Paging
}
if (dm.Take != 0)
{
DataSource = operation.PerformTake(DataSource, dm.Take);
}
var result = (ActionResult)(dm.RequiresCounts ? Json(new { result = DataSource, count = count }) : Json(DataSource));
return result;
}
public ActionResult CrudUpdate([FromBody]ICRUDModel<ManagementItem> value, string action)
{
//if (value.action == "update")
//{
// var ord = value.value;
// ManagementItem val = db.ManagementItems.Where(or => or.RowKey == ord.RowKey).FirstOrDefault();
// val.imagePrefix = ord.imagePrefix;
// val.imagesLocation = ord.imagesLocation;
// val.imagesResourceGroup = ord.imagesResourceGroup;
// val.imageVersion = ord.imageVersion;
// val.sourceResourceId = ord.sourceResourceId;
//}
//else if (value.action == "insert")
//{
// db.ManagementItems.Add(value.value);
//}
//else if (value.action == "remove")
//{
// db.ManagementItems.Remove(db.ManagementItems.Where(or => or.RowKey == value.key.ToString()).FirstOrDefault());
// return Json(value);
//}
//return Json(value.value);
return null;
}
public class ICRUDModel<T> where T : class
{
public string action { get; set; }
public string table { get; set; }
public string keyColumn { get; set; }
public object key { get; set; }
public T value { get; set; }
public List<T> added { get; set; }
public List<T> changed { get; set; }
public List<T> deleted { get; set; }
public IDictionary<string, object> #params { get; set; }
}
}
}
Use the DataGrid scaffold wizard. On the third page select DataSourceType = "Remote Data". A page and controller will be created with the correct code.
For your reference, we have created a sample and perform CRUD actions. Please refer the attached sample for more information.
Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/GridEJ2Mvc-914352281
The reported problem occurred when model mismatched. For Example, when we specify the number column field(EmployeeID) in grid but while inserting you did not specify the value for that column then it shows value as null in CrudUpdate, for this scenario you need to specify the nullable value for that field in model class as follows.
public class OrdersDetails
{
public OrdersDetails(int OrderID, string CustomerId, int EmployeeId, double Freight, bool Verified, DateTime OrderDate, string ShipCity, string ShipName, string ShipCountry, DateTime ShippedDate, string ShipAddress)
{
this.OrderID = OrderID;
this.CustomerID = CustomerId;
this.EmployeeID = EmployeeId;
. . . . .
}
public static List<OrdersDetails> GetAllRecords()
{
if (order.Count() == 0)
{
int code = 10000;
for (int i = 1; i < 10; i++)
{
order.Add(new OrdersDetails(code + 1, "ALFKI", i + 0, 2.3 * i, false, new DateTime(1991, 05, 15), "Berlin", "Simons bistro", "Denmark", new DateTime(1996, 7, 16), "Kirchgasse 6"));
. . . . .
}
}
return order;
}
public int? OrderID { get; set; }
public string CustomerID { get; set; }
public int? EmployeeID { get; set; } // it accept null value
. . . . .
}
}
If you still face the problem then share more details or below information that will helpful for us to validate further and provide a better solution as soon as possible.
• Did the problem occurred for both update and insert?
• Share package version details.
Regards,
Thavasianand S.

MvvmCross & MvxAdapter & Polymorphic Types with custom controls

I am currently trying to implement my own version of the polymorphic types demo that is located here:
https://github.com/MvvmCross/MvvmCross-Tutorials/tree/master/Working%20With%20Collections
And I have it working as the demo shows. However, I am looking to extend that demo to have more complex controls inside of the MvxListView. I am wanting to have each of the list items control a fragment that has a View and a core ViewModel for additional processing.
I am unsure of the correct way of implementing this.
The code that I am using to create the custom view is this:
protected override View GetBindableView(View convertView, Object source, Int32 templateId)
{
var listItem = (TodayPanel) source;
if (listItem != null)
templateId = (Int32) typeof (Resource.Layout).GetField(listItem.View).GetValue(null);
return base.GetBindableView(convertView, source, templateId);
}
As always, it's probably something simple that I am missing, but any help would be appreciated.
Thanks!
I hate it when this happens, but after posting my question, I stepped away from the computer for a little bit and started to do something else. At that point, everything clicked into place. Stuart, in response to your question, the TodayPanel was NOT an MvxModelView, and therein was the crux of the problem. What I was doing was passing a list of TodayPanels into the listview, which was an SQLite entity object and not an MvxModelView object.
For others that might be struggling with this, I am going to post my solution here.
So here is what I ended up doing. I first created a class for each of the TodayPanel entity objects that inherited from an abstract base class that inherited from MvxModelView.
public abstract class TodayBaseViewModel : MvxViewModel
{
protected TodayViewModel TodayViewModel { get; set; }
protected IDataService DataService { get; set; }
public String Name { get; set; }
public String Title { get; set; }
public Boolean CanHide { get; set; }
public Boolean Visible { get; set; }
public Int32 SortOrder { get; set; }
public String View { get; set; }
protected abstract void SetEventHandlers();
protected BaseViewModel(IDataService dataService)
{
DataService = dataService;
}
public void Init(TodayViewModel todayViewModel)
{
TodayViewModel = todayViewModel;
SetEventHandlers();
}
}
I made it abstract as I wanted 0 or more event handlers to be attached in the final class. which is done through the abstract SetEventHandlers() method:
public class CoachSaysViewModel : TodayBaseViewModel
{
public CoachSaysViewModel(IDataService dataService)
: base(dataService)
{
}
protected override void SetEventHandlers()
{
TodayViewModel.ConnectionUpdated += TodayViewModelConnectionUpdated;
TodayViewModel.NewActivityReceived += TodayViewModelNewActivityReceived;
}
protected void TodayViewModelNewActivityReceived(Object sender, EventArgs.ActivityReceivedEventArgs e)
{
}
protected void TodayViewModelConnectionUpdated(Object sender, EventArgs.ConnectionUpdatedEventArgs e)
{
}
}
Then I created an extension method that converts the TodayPanel entity to one of the classes that inherits from TodayBaseViewModel.
public static BaseViewModel ToBaseViewModel(this TodayPanel todayPanel, TodayViewModel todayViewModel)
{
BaseViewModel model = null;
switch (todayPanel.View)
{
case "Today_QuickView":
model = Mvx.IocConstruct<QuickViewViewModel>();
break;
case "Today_CoachSays":
model = Mvx.IocConstruct<CoachSaysViewModel>();
break;
}
if (model == null)
return null;
model.CanHide = todayPanel.CanHide;
model.Name = todayPanel.Name;
model.SortOrder = todayPanel.SortOrder;
model.Title = todayPanel.Title;
model.View = todayPanel.View;
model.Visible = todayPanel.Visible;
model.Init(todayViewModel);
return model;
}
That then allowed me to create a list of MvxViewModels that are then bound to the MvxListView and hence are allowed to do the additional processing that I am wanting to do.
I'm sure that there are some improvements that I can do to the end result, and if you see anything feel free to point it out. :)

Breeze Controller not returning proper response

I have a simple model, it is Entity Framework 5 Code First, ActiveEntity is an abstract class with an int Id property and a bool IsActive field.
public class License:ActiveEntity
{
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 LicenseType:ActiveEntity
{
[StringLength(100),Required]
public string Description { get; set; }
}
public class State:ActiveEntity
{
[StringLength(2)]
[Required]
public string Name { get; set; }
[Display(Name = "Long Name")]
[Required, StringLength(25)]
public string LongName { get; set; }
}
Breeze makes a call to GetLicenses on the LicenseController:
[BreezeController]
public class LicenseController : ApiController
{
private readonly EFContextProvider<LicensingContext> db = new EFContextProvider<LicensingContext>();
[HttpGet]
public string Metadata()
{
return db.Metadata();
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return db.SaveChanges(saveBundle);
}
[HttpGet]
public IQueryable<License> GetLicenses()
{
//for debugging purposes
var retVal = db.Context.Licenses
.Include(l => l.State)
.Include(l=>l.LicenseType);
return retVal;
}
}
The db context returns the appropriate data but it does not appear in the response.
I don't have enough reputation points to post an image but the license type and state are in the context's response.
However the controller's response does not contain the licensetype object for the first three objects.
[{"$id":"1","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"Low Voltage","State":{"$id":"2","$type":"Volt.Telecom.Licensing.Models.State, Volt.Telecom.Licensing.Models","Name":"FL","LongName":"Florida","IsActive":false,"Id":23},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":1},{"$id":"3","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"Contractors","State":{"$ref":"2"},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":2},{"$id":"4","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"General Contractors","State":{"$ref":"2"},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":3},{"$id":"5","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"Low Voltage","LicenseType":{"$id":"6","$type":"Volt.Telecom.Licensing.Models.LicenseType, Volt.Telecom.Licensing.Models","Description":"Low Voltage","IsActive":false,"Id":1},"State":{"$id":"7","$type":"Volt.Telecom.Licensing.Models.State, Volt.Telecom.Licensing.Models","Name":"CA","LongName":"California","IsActive":false,"Id":35},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":4},{"$id":"8","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"Contractors","LicenseType":{"$id":"9","$type":"Volt.Telecom.Licensing.Models.LicenseType, Volt.Telecom.Licensing.Models","Description":"Contractors","IsActive":false,"Id":2},"State":{"$ref":"7"},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":5},{"$id":"10","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"General Contractors","LicenseType":{"$id":"11","$type":"Volt.Telecom.Licensing.Models.LicenseType, Volt.Telecom.Licensing.Models","Description":"General Contractors","IsActive":false,"Id":3},"State":{"$ref":"7"},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":6}]
Here is the home.js file on the client.
define(['services/logger'], function (logger) {
var system = require('durandal/system');
var serviceName = 'api/License';
// manager is the service gateway and cache holder
var manager = new breeze.EntityManager(serviceName);
var vm = {
activate: getLicenses,
title: 'Licenses',
licenses: ko.observableArray(),
includeExpired: ko.observable(false),
save: saveChanges,
show: ko.observable(false)
};
//vm.includeExpired.subscribe(getLicenses);
function getLicenses() {
log("querying Licenses", null, true);
var query = breeze.EntityQuery.from("GetLicenses");
//if (!vm.includeExpired()) {
// query = query.where("DateIssued.AddDays(ValidFor*-1)" > new Date(Date.now()));
//}
return manager
.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
// reload vm.todos with the results
function querySucceeded(data) {
log("queried Licenses", null, true);
vm.licenses(data.results);
vm.show(true); // show the view
}
}
function queryFailed(error) {
log("Query failed: " + error.message, null, true);
}
function saveChanges() {
return manager.saveChanges()
.then(function () { log("changes saved", null, true); })
.fail(saveFailed);
}
function saveFailed(error) {
log("Save failed: " + error.message, null, true);
}
function log(msg, data, showToast) {
logger.log(msg, data, system.getModuleId(vm), showToast);
}
return vm;
//#endregion
});
Any thoughts as to why this would occur and only for the first three items, any help would be appreciated. I like breeze as a potential for some spa's we need to write but this has caused me some concern.
Update 1
If I change the order of the LicenseType_id in the database it works, the initial order was 123123
if it is changed to 312123 or 321123 all six are correct in the response
[{"$id":"1","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"Low Voltage","LicenseType":{"$id":"2","$type":"Volt.Telecom.Licensing.Models.LicenseType, Volt.Telecom.Licensing.Models","Description":"General Contractors","IsActive":false,"Id":3},"State":{"$id":"3","$type":"Volt.Telecom.Licensing.Models.State, Volt.Telecom.Licensing.Models","Name":"FL","LongName":"Florida","IsActive":false,"Id":23},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":1},{"$id":"4","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"Contractors","LicenseType":{"$id":"5","$type":"Volt.Telecom.Licensing.Models.LicenseType, Volt.Telecom.Licensing.Models","Description":"Low Voltage","IsActive":false,"Id":1},"State":{"$ref":"3"},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":2},{"$id":"6","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"General Contractors","LicenseType":{"$id":"7","$type":"Volt.Telecom.Licensing.Models.LicenseType, Volt.Telecom.Licensing.Models","Description":"Contractors","IsActive":false,"Id":2},"State":{"$ref":"3"},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":3},{"$id":"8","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"Low Voltage","LicenseType":{"$ref":"5"},"State":{"$id":"9","$type":"Volt.Telecom.Licensing.Models.State, Volt.Telecom.Licensing.Models","Name":"CA","LongName":"California","IsActive":false,"Id":35},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":4},{"$id":"10","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"Contractors","LicenseType":{"$ref":"7"},"State":{"$ref":"9"},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":5},{"$id":"11","$type":"Volt.Telecom.Licensing.Models.License, Volt.Telecom.Licensing.Models","LicenseName":"General Contractors","LicenseType":{"$ref":"2"},"State":{"$ref":"9"},"DateIssued":"2012-11-18T00:00:00.000","ValidFor":1095,"IsActive":false,"Id":6}]
Edit: As of v 1.3.1 Breeze now DOES support inheritance.
The problem may be that Breeze does not yet support inheritance. There is a UserVoice suggestion here. Please vote on it. We take these suggestions very seriously.
To confirm that this is your issue, can you flatten the structure so that you do not need inheritance and see if the issue goes away.
I think that if something disappears between server to client its because Breeze retain null data column which can disorganize data structure and make knockout binding dysfunctional.
In opting to minimize Breeze performance you can place the attribute in the down level according to your need.
1 - BreezeWebApiConfig.cs level
2 - Controller level
3 - or HttGet level
This attribute works for me:
var jsonx = Breeze.WebApi.BreezeConfig.Instance;
jsonx.GetJsonSerializerSettings().NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;

MVC Multiple Databases in one single domain model

I am writting an app based on Steve Sanderson's Pro Asp .Net MVC Framework, which uses a data modeling like described on Sports Store app on that book. My app works well, I use Castle project as IOC but I have two databases. The first one stores many kind of data and my clients information. The second one stores only medical data of each client. I need to create a class that returns data in clients table, located on database 1 and medical information of each client stored on database 2.
Below are my code:
My connectionstrings on web.config:
<add name="CNRConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=CNR;Persist Security Info=True;User ID=sa;Password=#####!" providerName="System.Data.SqlClient"/>
<add name="CNRpeConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=pe;Persist Security Info=True;User ID=sa;Password=#####!" providerName="System.Data.SqlClient"/>
My new class (just data, no table conection):
namespace DomainModel.Entities
{
public class ImprimePeriodoPaciente
{
public int CodConsulta { get; set; }
public DateTime DataConsulta { get; set; }
public string Evolucao { get; set; }
public int CodProfissional1 { get; set; }
public int CodPaciente1 { get; set; }
public string NomeProfissional { get; set; } //receives data from other db
public string NomePaciente { get; set; } //receives data from other db
public int CodProcedimento { get; set; }
public bool TagConsulta { get; set; }
public int? TagConsulta2 { get; set; }
public DateTime di { get; set; }
public DateTime df { get; set; }
}
}
This is my concrete and interface from domainmodel:
public class SqlConsultasRepository:IConsultasRepository
{
private Table<Consulta> consultasTabela;
private Table<TEvolucao> tEvolucaoTabela;
private Table<Paciente> pacientesTabela;
private Table<Funcionario> funcionariosTabela;
public SqlConsultasRepository(string connectionString)
{
consultasTabela = (new DataContext(connectionString)).GetTable<Consulta>();
tEvolucaoTabela = (new DataContext(connectionString)).GetTable<TEvolucao>();
pacientesTabela = (new DataContext(connectionString)).GetTable<Paciente>();
funcionariosTabela = (new DataContext(connectionString)).GetTable<Funcionario>();
}
public IQueryable<ImprimePeriodoPaciente> Prontuarios {
get
{
return
(
from c in consultasTabela
join p in pacientesTabela on c.CodPaciente1 equals p.CodigoPaciente //my doom
join f in funcionariosTabela on c.CodProfissional1 equals f.CodigoFuncionario //my doom
select new ImprimePeriodoPaciente
{
CodConsulta=c.CodConsulta,
DataConsulta=c.DataConsulta,
Evolucao=c.Evolucao,
NomeProfissional= f.NomeFuncionario, //my doom
NomePaciente=p.NomePaciente, //my doom
CodProfissional1=c.CodProfissional1,
CodPaciente1 = c.CodPaciente1
}
);
}
}
The code is marked with 'my doom' to show where the problem occurs.... I need to create a connectionString reference to the other database because this tables are not in current database specified by connectionString variable. I am getting error saying that the data are not from same datacontext (or shomething like that).
So, could you help?
Got my way through it based on this post:
http://dotnetprogrammingtipsbymuhil.blogspot.com.br/2009/12/query-contains-references-to-items.html
For those who get on same problem, follow above post steps.
Im my project I've created an interface to a concrete method that takes separated data from each database and put them on separated lists, as follows:
namespace DomainModel.Concrete
{
public class SqlImprimePeriodoPacientesRepository : IImprimePeriodoPacientesRepository
{
private static string cConexao = "Data Source=.\\SQLEXPRESS;Initial Catalog=CNR;Persist Security Info=True;User ID=sa;Password=23092000";
private static string cConexao2 = "Data Source=.\\SQLEXPRESS;Initial Catalog=PE;Persist Security Info=True;User ID=sa;Password=23092000";
private IConsultasRepository cRepository = new SqlConsultasRepository(cConexao2);
private IPacientesRepository pRepisotory = new SqlPacientesRepository(cConexao);
private IFuncionariosRepository fRepository = new SqlFuncionariosRepository(cConexao);
public IQueryable<ImprimePeriodoPaciente> ImprimePeriodoProntuarios//(int? codpac, DateTime? di, DateTime? df)
{
get
{
var consultas =
(
from c in cRepository.Consultas
select new
{
c.cdf,
c.cdi,
c.CodConsulta,
c.CodPaciente1,
c.CodProcedimento,
c.CodProfissional1,
c.DataConsulta,
c.df,
c.di,
c.Evolucao,
c.TagConsulta,
c.TagConsulta2
}
)
.ToList();
var pacientes =
(
from p in pRepisotory.Pacientes
select new
{
p.CodigoPaciente,
p.NomePaciente
}
)
.ToList();
var funcionarios =
(
from f in fRepository.Funcionarios
select new
{
f.CodigoFuncionario,
f.NomeFuncionario
}
)
.ToList();
var result =
(
from c in consultas
join p in pacientes on c.CodPaciente1 equals p.CodigoPaciente
join f in funcionarios on c.CodProfissional1 equals f.CodigoFuncionario
select new ImprimePeriodoPaciente
{
CodConsulta = c.CodConsulta,
DataConsulta = c.DataConsulta,
Evolucao = c.Evolucao,
NomeProfissional = f.NomeFuncionario,
NomePaciente = p.NomePaciente,
CodProfissional1 = c.CodProfissional1,
CodPaciente1 = c.CodPaciente1
}
).ToList();
return result.AsQueryable();
}
}
}
}
That method did the job on the Domain´s Model side, so the rest resides on dealing with the results.
Hope this help someone!

Entity framework savechanges error

I have a wizard step in which a user fills in fields. I then use json to save the values into my database for each wizard step.
However, in my repository I have my savechanges(). But it wont save the changes, instead it throws an error:
Entities in 'NKImodeledmxContainer.SelectedQuestion' participate in the 'QuestionSelectedQuestion' relationship. 0 related 'Question' were found. 1 'Question' is expected.
Anyone know how to get rid of the error? Do I have to get the ID from Question and save it aswell to my database or can I change something in EF so the error message is not getting thrown?
This is my post in my controller:
[HttpPost]
public JsonResult AnswerForm(int id, SelectedQuestionViewModel model)
{
bool result = false;
var goalCardQuestionAnswer = new GoalCardQuestionAnswer();
goalCardQuestionAnswer.SelectedQuestion = new SelectedQuestion();
goalCardQuestionAnswer.SelectedQuestion.Id = model.QuestionID;
goalCardQuestionAnswer.Comment = model.Comment;
goalCardQuestionAnswer.Grade = model.Grade;
if (goalCardQuestionAnswer.Grade != null)
{
answerNKIRepository.SaveQuestionAnswer(goalCardQuestionAnswer);
answerNKIRepository.Save();
result = true;
return Json(result);
}
answerNKIRepository.SaveQuestionAnswer(goalCardQuestionAnswer);
answerNKIRepository.Save();
return Json(result);
}
My Repository
public class AnswerNKIRepository
{
private readonly NKImodeledmxContainer db = new NKImodeledmxContainer();
public List<SelectedQuestion> GetAllSelectedQuestionsByGoalCardId(int goalCardId)
{
return db.SelectedQuestion.Where(question => question.GoalCard.Id == goalCardId).ToList();
}
public void SaveQuestionAnswer(GoalCardQuestionAnswer goalCardQuestionAnswer)
{
db.GoalCardQuestionAnswer.AddObject(goalCardQuestionAnswer);
}
public void Save()
{
db.SaveChanges();
}
}
This is my ViewModel:
public class SelectedQuestionViewModel
{
public int? Grade { get; set; }
public string Comment { get; set; }
public string SelectedQuestionText { get; set; }
public int QuestionID { get; set; }
}
This is my database model:
The exception complains that SelectedQuestion.Question is a required navigation property but you don't set this property in your code. Try to load the question by Id from the repository and set it to the SelectedQuestion.Question reference: Replace this line ...
goalCardQuestionAnswer.SelectedQuestion.Id = model.QuestionID;
...by...
goalCardQuestionAnswer.SelectedQuestion.Question =
answerNKIRepository.GetQuestionById(model.QuestionID);
And in your repository add the method:
public Question GetQuestionById(int id)
{
return db.Question.Single(q => q.Id == id);
}

Resources