WPF Binding problem - binding

I have a class structure as follows :
public class Person
{
public PersonInfo Details { get; set; }
public string Name { get; set; }
}
public class PersonInfo
{
public string Designation { get; set; }
}
I am trying bind 2 textBoxes as follows:
Person person = new Person();
textBox1.DataContext = person;
textBox2.DataContext = person;
Binding textBox1Binding = new Binding()
{
Mode = BindingMode.OneWayToSource,
Path = new PropertyPath("Name"),
};
Binding textBox1Binding = new Binding()
{
Mode = BindingMode.OneWayToSource,
**Path = new PropertyPath("Details.Designation")** << problem is here
};
How to bind "Details.Designation" to textbox2 ?
Any help would be appreciated.

It took some time, but I think I have a solution. Your PersonInfo-Object in Person does not exist. I modified your code to the following and now it works for me
public class Person
{
private PersonInfo pi;
public Person()
{
pi = new PersonInfo();
}
public PersonInfo Details
{
get
{
return pi;
}
set
{
pi = value;
}
}
public string Name { get; set; }
}
public class PersonInfo
{
public string Designation { get; set; }
}
And somewhere:
textBox1.DataContext = person;
textBox2.DataContext = person;
Binding textBox1Binding = new Binding()
{
Mode = BindingMode.OneWayToSource,
Path = new PropertyPath("Name"),
};
textBox1.SetBinding(TextBox.TextProperty, textBox1Binding);
Binding textBox2Binding = new Binding()
{
Mode = BindingMode.OneWayToSource,
Path = new PropertyPath("Details.Designation"),
};
textBox2.SetBinding(TextBox.TextProperty, textBox2Binding);
Can you ensure that your Sub-Object 'PersonInfo' (via Property Designation) exists before binding?

Related

.Net Core - Method Create Error NullReferenceException

There are already some questions about this problem, but none of them actually solved my problem.
I'm trying to create the Create method of the Student.cs entity, but when I access the create url, this error appears, I really do not know how to solve it.
AlumniController.cs
line error: 32 var teachers = await _contextProfessor.FindAllAsync ();
Image error
Code
AlunoController.cs
public class AlunosController : Controller
{
public readonly AlunosService _contextAluno;
public readonly ProfessorService _contextProfessor;
public readonly TurmasController _contextTurma;
public AlunosController(AlunosService contextAluno)
{
_contextAluno = contextAluno;
}
public async Task<IActionResult> Index()
{
var lista = await _contextAluno.FindAllAsync();
return View(lista);
}
//GET
public async Task<IActionResult> Create()
{
var professores = await _contextProfessor.FindAllAsync();
var turmas = await _contextTurma.FindAllAsync();
var viewModel = new AlunoViewModel {
Professores = professores,
Turmas = turmas
};
return View(viewModel);
}
}
Turma.cs
public class Turma
{
public int Id { get; set; }
public int Numero { get; set; }
public string Curso { get; set; }
public ICollection<Aluno> Alunos { get; set; } = new List<Aluno>();
public Turma()
{
}
public Turma(int id, int numero, string curso)
{
Id = id;
Numero = numero;
Curso = curso;
}
}
Professor.cs
public class Professor
{
public int Id { get; set; }
public string Nome { get; set; }
public string Email { get; set; }
public string Telefone { get; set; }
public ICollection<Aluno> Alunos { get; set; } = new List<Aluno>();
public Professor()
{
}
public Professor(int id, string nome, string email, string telefone)
{
Id = id;
Nome = nome;
Email = email;
Telefone = telefone;
}
}
How can I solve this?
Code Complete HERE.
_contextProfessor is null. You will need to set it in the constructor of AlunosController.
public AlunosController(AlunosService contextAluno, ProfessorService professorService)
{
_contextAluno = contextAluno;
_contextProfessor = processorService;
}
You obviously have not assigned objects to _contextProfessor and _contextTurma fields, so you will naturally get a NullReferenceException if you try to refer to their methods and properties. So, firstly, you need to inject ProfessorService and TurmasController into controller constructor.
But for injection to be successfull, you need to specify the dependecies in your Startup class ConfigureServices method, otherwise the dependecy won't be able to be resolved an InvaidOperationException will be thrown.
Because you forgot to include that service in the call in the constructor
public AlunosController(AlunosService contextAluno, ProfessorService contextProfessor)
//^^^^
{
_contextAluno = contextAluno;
_contextPrefessor = contextProfessor;
}
DI bit you a little. just because you add the one context to the constructor doesn't mean the others are instantiated for free.

How to retrieve a data from database?

I have a question about how to get data from a database.
This is my code so far:
public class TabController : Controller
{
private TestEntities db = new TestEntities();
public ActionResult Index()
{
var model = GetTab();
return View(model);
}
private IEnumerable<MN_REITER> GetReiter()
{
var reiters = Enumerable.Range(0,5).Select(
i => new MN_REITER
{
TabId = i,
TabDescription = "Tab "+i
//REITER_LABEL = "Label" + i
});
return reiters;
}
Like answer a have a Tab0 to Tab5, but I want a get the information from database.
Edit:
View.cshtml
#model IEnumerable >rcMDM.Data.MN_REITER>
(Html.Kendo().TabStrip()
.Name("reiterTab")
.BindTo(Model, (item, reiter)=>
{
item.Text = reiter.REITER_BEZEICHNUNG;
// item.Template.Html = reiter.REITER_LABEL;
})
and the model
public partial class MN_REITER
{
public decimal REITERID { get; set; }
public string REITER_BEZEICHNUNG { get; set; }
public string REITER_LABEL { get; set; }
}
}

Httpget Method using asp.net mvc in controller

Fetch data from database some error occur here (AdminPurpose con = i.a ) Message show Cannot implicitly converted type.Please see below for my code snippets:
public JsonResult GetInfor()
{
List<AdminPurpose> all = new List<AdminPurpose>();;
using (db_Hajj_UmrahEntities dc= new db_Hajj_UmrahEntities()) {
var datas = (from a in dc.Duas join b in dc.Purposes on a.PurposeId equals b.Id
select new {
a,
b.PurPose1
});
if(datas != null) {
foreach (var i in datas)
{
AdminPurpose con = i.a ;
con.PurPose1 = i.PurPose1;
all.Add(con);
}
}
}
return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Model class one to many relation here it's using
[MetadataType(typeof(DuaMetaData))]
public partial class AdminPurpose
{
public string PurPose1 { get; set; }
}
public class DuaMetaData
{
public string Dua_Name { get; set; }
public string Arabic_Word { get; set; }
public string Translation_English { get; set; }
public string Source { get; set; }
[Display(Name = "Purpose")]
public int PurposeId { get; set; }
}

Exception: Multiplicity constraint violated

After changing relationship of Question and PossibleAnswer from Many-to-many to One-to-many I got an exception: "The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: Multiplicity constraint violated. The role 'PossibleAnswer_Question_Source' of the relationship 'WebUI.Models.PossibleAnswer_Question' has multiplicity 1 or 0..1." What does it mean?
Here is my model:
public class Question
{
public int ID { get; set; }
public string Text { get; set; }
public bool IsAssociatedWithProfessor { get; set; }
public bool IsAssociatedWithAssistant { get; set; }
public virtual ICollection<PossibleAnswer> PossibleAnswers { get; set; }
public virtual ICollection<Results> Results { get; set; }
}
public class PossibleAnswer
{
public int ID { get; set; }
public string Text { get; set; }
public virtual Question Question { get; set; }
}
And view model for Question (I know that ToQuestion should be in controller, I will rearrange it later):
public class QuestionVM
{
public QuestionVM() {
}
public QuestionVM(Question question) : this()
{
ID = question.ID;
Text = question.Text;
IsAssociatedWithProfessor = question.IsAssociatedWithProfessor;
IsAssociatedWithAssistant = question.IsAssociatedWithAssistant;
}
public int? ID { get; set; }
public string Text { get; set; }
public bool IsAssociatedWithProfessor { get; set; }
public bool IsAssociatedWithAssistant { get; set; }
private IEnumerable<string> _possibleAnswers;
public IEnumerable<string> PossibleAnswers
{
get
{
return _possibleAnswers ?? new List<string>(){"", "", "", "", ""};
}
set
{
_possibleAnswers = value;
}
}
public Question ToQuestion()
{
Question question = new Question
{
Text = this.Text,
IsAssociatedWithProfessor = this.IsAssociatedWithProfessor,
IsAssociatedWithAssistant = this.IsAssociatedWithAssistant,
PossibleAnswers = new List<PossibleAnswer>()
};
//ID will be null if creating new question
if(ID != null)
{
question.ID = (int) ID;
}
foreach (string possibleAnswer in this.PossibleAnswers)
{
if (!String.IsNullOrEmpty(possibleAnswer))
{
question.PossibleAnswers.Add(new PossibleAnswer { Text = possibleAnswer });
}
}
return question;
}
}
Here is my post method for creating new question:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddQuestion(QuestionVM questionVM)
{
try
{
if (ModelState.IsValid)
{
Question question = questionVM.ToQuestion();
context.Questions.Add(question);
context.SaveChanges();
return RedirectToAction("Questions");
}
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Trenutno nije moguće snimiti promjene, pokušajte ponovo.");
}
return View(questionVM);
}
Line:question.PossibleAnswers.Add(new PossibleAnswer { Text = possibleAnswer });
causes the exception since I didn't save possible answers in database before I am adding them to question... But how can I add them to database without use of DbContext (since it is not a good practice to use DbContext in method which converts view model to model)?
Error is coming because PossibleAnswers are not being marked as added entity.
So update your QuestionVM like below:
public class QuestionVM
{
public QuestionVM() {
}
public QuestionVM(Question question) : this()
{
ID = question.ID;
Text = question.Text;
IsAssociatedWithProfessor = question.IsAssociatedWithProfessor;
IsAssociatedWithAssistant = question.IsAssociatedWithAssistant;
}
public int? ID { get; set; }
public string Text { get; set; }
public bool IsAssociatedWithProfessor { get; set; }
public bool IsAssociatedWithAssistant { get; set; }
private IEnumerable<string> _possibleAnswers;
public IEnumerable<string> PossibleAnswers
{
get
{
return _possibleAnswers ?? new List<string>(){"", "", "", "", ""};
}
set
{
_possibleAnswers = value;
}
}
public Question ToQuestion()
{
Question question = new Question
{
Text = this.Text,
IsAssociatedWithProfessor = this.IsAssociatedWithProfessor,
IsAssociatedWithAssistant = this.IsAssociatedWithAssistant,
PossibleAnswers = new List<PossibleAnswer>()
};
//ID will be null if creating new question
if(ID != null)
{
question.ID = (int) ID;
}
return question;
}
public List<PossibleAnswer> GetPosibleAnswers()
{
var listOfPossibleAnswers = new List<PossibleAnswer>();
foreach (string possibleAnswer in this.PossibleAnswers)
{
if (!String.IsNullOrEmpty(possibleAnswer))
{
listOfPossibleAnswers.Add(new PossibleAnswer { Text = possibleAnswer });
}
}
return listOfPossibleAnswers;
}
}
and then update your code like below.
if (ModelState.IsValid)
{
Question question = questionVM.ToQuestion();
context.Questions.Add(question);
context.SaveChanges();
question.PossibleAnswers.AddRange(questionVM.GetPosibleAnswers());
context.SaveChanges();
return RedirectToAction("Questions");
}

CTP5 POCO Code-Only, how to add master-detail records to DB

I am trying EF CTP5 POCO, and converting from EF4 EntityModel to POCO Code Only Approach.
internal class InvoiceContext : DbContext
{
public DbSet<Invoice> Invoices {get; set;}
public DbSet<InvoiceLine> InvoiceLines {get; set;}
}
public class Invoice
{
public Guid InvoiceId { get; set; }
public virtual ICollection<InvoiceLine> Lines { get; set; }
}
public class InvoiceLine
{
public Guid InvoiceLineId { get; set; }
public Guid InvoiceId { get; set; }
public virtual Invoice Header { get; set; }
}
so converting my old code from EF4 Model to POCO, I am supposed to add new Invoice and Lines. I used to create the master class and add the details to the instance of the master class itself.
var inv = new Invoice();
inv.InvoiceId = Guid.NewGuid();
var db = new InvoiceContext();
db.Invoices.Add(inv);
var invLine = new InvoiceLine();
invLine = InvoiceLineId = Guid.NewGuid();
inv.Lines.Add(invLine);
inv.Lines <== is null at this point, so I cannot add a line to the instance of the invoice itself
am I supposed to create a collection of InvoiceLines and set it, or is there some other way to do this.
So in short, how I can add master/detail rows to my database using POCO Code Only (CTP5).
Here is one way to do this:
using (var db = new Ctp5Context())
{
var inv = new Invoice()
{
InvoiceId = Guid.NewGuid()
};
var invLine = new InvoiceLine()
{
InvoiceLineId = Guid.NewGuid(),
Header = inv
};
db.InvoiceLines.Add(invLine);
db.SaveChanges();
}
If you prefer to add an invoice object then:
using (var db = new Ctp5Context())
{
var invLine = new InvoiceLine()
{
InvoiceLineId = Guid.NewGuid()
};
var inv = new Invoice()
{
InvoiceId = Guid.NewGuid(),
Lines = new List<InvoiceLine>() { invLine}
};
db.Invoices.Add(inv);
db.SaveChanges();
}
While all these works, I recommend always initialize the collection of navigation property in the class constructors so that you don't need to do it in the client code every single time as well as there is no chance of hitting NullReferenceException in the runtime:
public class Invoice
{
public Invoice()
{
Lines = new List<InvoiceLine>();
}
public Guid InvoiceId { get; set; }
public virtual ICollection<InvoiceLine> Lines { get; set; }
}
...
using (var db = new Ctp5Context())
{
var invLine = new InvoiceLine()
{
InvoiceLineId = Guid.NewGuid()
};
var inv = new Invoice()
{
InvoiceId = Guid.NewGuid(),
};
inv.Lines.Add(invLine);
db.Invoices.Add(inv);
db.SaveChanges();
}

Resources