Linq to SQL ADD and Update - winforms

As you can tell from my code, I'm absolute a beginner. After searching through other similar issues on LINQ to SQL problems, I find myself still seemingly stuck on two objectives. 1) Adding a new entry with input from the user selection from three comboboxes and a datepicker and 2) Updating an existing database entry using interactions from the datagridview.
My windows form datagridview is displaying the following output
**select b.Date, a.EmployeeName,
c.ProjectName, b.Hours
from dbo.Employees a
left outer join dbo.EmployeeProjectHours b
on a.EmployeeId = b.EmployeeId
left outer join dbo.Projects c
on b.ProjectId = c.ProjectId**
Here is my ADD method the user is providing me with ProjectName, EmployeeName, Date and Hours. Any thoughts for a layman would be appreciated.
I don't get an error running the insert, but nothing is added to my dab as well
using (ProjectHoursDataContext dbInsert = new ProjectHoursDataContext())
{
this.Validate();
EmployeeProjectHour empHours = new EmployeeProjectHour();
empHours.Date = dateDateTimePicker.Value;
empHours.Hours = Convert.ToDecimal(hoursComboBox.Text);
empHours.ProjectId = dbInsert.Projects.First(p => p.ProjectName == projectNameComboBox.Text).ProjectId;
empHours.EmployeeId = dbInsert.Employees.First(m => m.EmployeeName == employeeNameComboBox.Text).EmployeeId;
db.EmployeeProjectHours.InsertOnSubmit(empHours);
dbInsert.SubmitChanges();
}
Here is my Update attempting to use updates directly from the datagridview. I get the following error: A first chance exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll
using (ProjectHoursDataContext dbUpdate = new ProjectHoursDataContext())
{
this.Validate();
dataGridView1.AutoGenerateColumns = true;
projectBindingSource.DataSource = dbUpdate;
projectBindingSource.DataMember = "Updates";
projectBindingSource.EndEdit();
dbUpdate.SubmitChanges();
}

My best guess so far is, you want to edit and change existing Employee, Project and EmployeeProjectHours records.
So you would do:
using (ProjectHoursDataContext dbInsert = new ProjectHoursDataContext())
{
this.Validate();
// Get the records
Employee emp = new Employee();
Project proj = new Project();
EmployeeProjectHour empHours = new EmployeeProjectHour();
// Set new values to Employees tables
emp = dbInsert.Employees
.First(m => m.EmployeeName == employeeNameComboBox.Text);
//just get the empployee
//setting values will update it
emp.EmployeeName = employeeNameComboBox.Text;
// GET an existing project
proj = dbInsert.Projects
.First(p => p.ProjectName == projectNameComboBox.Text);
//update its values.
proj.ProjectName = projectNameComboBox.Text;
proj.ProjectDescription = "Test";
//GET an empHours
empHours = dbInsert.Projects.First(p => p.EmployeeId == emp.EmployeeId &&
p.ProjectId == proj.ProjectId);
//set its values
empHours.Date = dateDateTimePicker.Value;
empHours.Hours = Convert.ToDecimal(hoursComboBox.Text);
dbInsert.SubmitChanges();
}

Aside from the new code below, I also set my increment status for my projects database to NO. I had set it yes from a previous stackoverflow discussion. Thanks
public void AddInfo()
{
db.Connection.Open();
this.Validate();
EmployeeProjectHour empHours = new EmployeeProjectHour();
empHours.Date = dateDateTimePicker.Value;
empHours.Hours = Convert.ToDecimal(hoursComboBox.Text);
empHours.ProjectId = db.Projects.First(p => p.ProjectName == projectNameComboBox.Text).ProjectId;
empHours.EmployeeId = db.Employees.First(m => m.EmployeeName == employeeNameComboBox.Text).EmployeeId;
db.EmployeeProjectHours.InsertOnSubmit(empHours);
db.SubmitChanges();
db.Connection.Close();
}

Related

C# joined tables contains null after execution (.NET Core, EF database-first)

I am using a database-first approach with Entity Framework in .NET Core which ends up using this. Some tables are with a relationship in SQL Server which results joined in code.
I was about to get a DateTime on a joined table and want to give a string format, but to do it I should execute first the query so I could give a format to it like what was mentioned here. The question is, why did the joined table go null after the execution?
To explain my problem easily here's the code:
var a = (from p in db.Product
select s).ToList();
var b = (from p in a
select p.Brand.DateCreated.ToString("MMMM dd, yyyy")).ToList();
// Brand contains null after execution in "a"
var c = (from p in db.Product
select p.Brand.DateCreated.ToString("MMMM dd, yyyy")).ToList();
// Brand contains data but execution gives error due to DateTime.ToString()
In the meantime, This is my solution but I need to create another Model. Which will end up a lot of Model just for this case.
public class ProductBrand
{
public class Product { get; set; }
public class Brand { get; set; }
}
var a = (from s in db.Product
select new ProductBrand {
Product = s,
Brand = s.Brand,
}).ToList().Select(s => s.Brand.DateCreated.ToString("MMMM dd, yyyy")).ToList();
EDITTED:
Above problem was solved by just updating my Model. But problem related to above question still encounter. When saving new Product the Brand becomes null after saving
To explain my problem easily here's the code:
var p = new Product { Name = "temp", BrandId = 1 };
db.Product.Add(p);
db.SaveChanged();
return p.Brand.DateCreated.ToString("MMMM dd, yyyy"); // but Brand is null
In the meantime
var p = new Product { Name = "temp", BrandId = 1 };
db.Product.Add(p);
db.SaveChanged();
if(p.Brand == null) { // Here's my temporary solution, but how about for those tables with lot of joins
p.Brand = db.Brand.FirstOrDefault(s => s.Id == p.BrandId);
}
return p.Brand.DateCreated.ToString("MMMM dd, yyyy");
Did I miss something?

Consulting two databases and three tables (Entity Framework, SQL Server)

I'm working on a MVC .NET application using EF.
I have a JqGrid in my view which works correctly bringing data from one table, but the information that I need is in two databases and three tables (Database is not normalized correctly, it sucks). I already have my two context (edmx) created in my project, I just had no idea on how to proceed in my Model. Here is my query which works fine in SQL Server
SELECT
a.idPlanta, a.idArticulo, b.DescripcionCorta, c.Planta,
a.FechaAlta, a.Existencia
FROM
CAT_ArticulosEnPlanta AS a
INNER JOIN
CAT_Articulos AS b ON a.idArticulo = b.idArticulo
INNER JOIN
[LEC].[dbo].[Plantas] AS c ON a.idPlanta = c.PlantaID
ORDER BY
b.DescripcionCorta ASC;
and here is my model that brings information from one table
public List<ArticulosPlantaView> GetArticulosEnPlanta()
{
List<ArticulosPlantaView> articuloss = new List<ArticulosPlantaView>();
using (TemakaSoftTestEntities TSTE = new TemakaSoftTestEntities())
{
ArticulosPlantaView APV;
foreach (CAT_ArticulosEnPlanta a in TSTE.CAT_ArticulosEnPlanta)
{
APV = new ArticulosPlantaView();
APV.idArticulo = a.idArticulo;
APV.idPlanta = a.idPlanta;
APV.idUsuarioAlta = a.idUsuarioAlta;
APV.FechaAlta = a.FechaAlta;
APV.Existencia = a.Existencia;
APV.Comentarios = a.Comentarios;
APV.idUsuarioElimina = a.idUsuarioElimina;
APV.FechaEliminacion = a.FechaEliminacion;
APV.Visible = a.Visible;
articuloss.Add(APV);
}
return articuloss;
}
}
public ArticulosPlantaDataView GetArticulosPlantaDataView()
{
ArticulosPlantaDataView APDV = new ArticulosPlantaDataView();
List<ArticulosPlantaView> articuloss = GetArticulosEnPlanta();
APDV.articulos = articuloss;
return APDV;
}
An example will help a lot.
THANK YOU VERY MUCH!!!

Update record using linq with ADO.NET with Oracle

I have created an ADO.NET entity data model, and using linq to update/edit my oracle database.
using (Entities ent = new Entities())
{
RUSHPRIORITYRATE rp = new RUSHPRIORITYRATE();
rp.RATE = rate;
var query = from j in ent.RUSHPRIORITYRATEs
select j;
List<RUSHPRIORITYRATE> list = query.ToList();
if (list.Count == 0)
{
ent.AddToRUSHPRIORITYRATEs(rp);
ent.SaveChanges();
}
else
{
foreach (RUSHPRIORITYRATE r in query)
{
r.RATE = rp.RATE;
}
ent.SaveChanges();
}
}
I have a method that either adds or updates a Table that will always have one record. The record's value is then only update once there is one record in place. Adding to the table is no problem, but I've looked up how to update recores through MSDN, and "ent" does not seem to have the "submitchanges" method that the solution requires. Running this, I get the error: "The property 'RATE' is part of the object's key information and cannot be modified."

Select element in WPF Combobox from Nhibernate

I have a dude, i want to select a value from wpf Combobox
I have the next code:
private void CargarUnidades()
{
List<Unidades> unidades;
using (var sesion = NHibernateFluentConfiguracion.AbrirSesion())
{
using (var transaccion = sesion.BeginTransaction())
{
unidades = Unidades.ObtenerTodaslasUnidades();
}
}
cmbUnidad.ItemsSource = unidades;
cmbUnidad.DisplayMemberPath = "Nombre";
cmbUnidad.SelectedValuePath = "Nombre";
}
After I charge the unidades
CargarUnidades(); //Charge all unidades in the combobox
Articulos c = Articulos.Obtener(id_articulo);
//Get Articulo from the database for the id
//In the last query I get the unidad same that exists in cmbUnidad
//previusly charge
//I assing the value but in the combobox doesnt appear selected,
//appear nothing
cmbUnidad.SelectedValue = c.id_unidad;
txtCodigo.Text = c.Codigo;
.
.
.
.
How I can select a value from combobox???
Note: I m new in WPF and my english is not good je je je
Thanks for the answer Firo, I modify the code and this is the result
cmbUnidad.Items.Cast<Unidades>().FirstOrDefault(u => u.id_unidad == c.id_unidad.id_unidad);
I dont know if this is the best way but its functionaly :P
selectedValue must euqal (using Equals) with one of the values in the list hence assign the object not the id because the control does not know how to select based on the id
cmbUnidad.SelectedValue = c;
UPDATE: since the Articulos has only the id of unidades and not a reference (which i would have mapped) you have to search for it.
cmbUnidad.SelectedValue = cmbUnidad.Items.Cast<Unidades>().FirstOrDefault(u => u.Nombre == c.id_unidad);

Datagrid duplicates one item from source

I have a RIA service that is to return a list of schools and populate a datagrid. This datagrid is duplicating the first result throughout the entire grid, as opposed to showing each item from source in its own row.
The service is as follows
var schools1 = (from i in DataContext.PrevSchools
join skl in DataContext.SchoolLists on i.School_id equals skl.School_Id
where i.Email_Address == email
select new PreviousSchools
{
PrevSchoolsId = i.PrevSchools_id,
AppEmail = i.Email_Address,
SchoolId = i.School_id,
DateAttended = i.YearsAttended,
Study = i.Study,
Credit = i.Credit,
CompleteStatus = i.Complete_Status,
Award = i.Award,
SchoolName = skl.School_name
}).Union(from i in DataContext.PrevSchools
join skl1 in DataContext.Schools on i.School_id equals skl1.School_id
where i.Email_Address == email && i.School_type_id == 1
select new PreviousSchools
{
PrevSchoolsId = i.PrevSchools_id,
AppEmail = i.Email_Address,
SchoolId = i.School_id,
DateAttended = i.YearsAttended,
Study = i.Study,
Credit = i.Credit,
CompleteStatus = i.Complete_Status,
Award = i.Award,
SchoolName = skl1.School_name
}).OrderBy(q => q.SchoolName);
return schools1;
The Databinding is:
this.PrevSchools.prevSchoolDataGrid.DataContext = SchoolsList;
The SchoolList is an ObservableCollection, it was set as a list and also a, IEnumerable, and it still yielded the duplicated results.
Fixed it, it was an error in the Model class, the key was set to the wrong property

Resources