public class Project
{
public string ProjectName { get; set; }
public string Startdate { get; set; }
public string Enddate { get; set; }
public int? id { get; set; }
public Project(string projectname, string startdate, string enddate, int Id)
{
this.ProjectName = projectname;
this.Startdate = startdate;
this.Enddate = enddate;
this.id = Id;
}
public Project()
{
}
}
public class Employee
{
public int EmployeeID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string mobile { get; set; }
public string address { get; set; }
public int roleid { get; set; }
public string roleName { get; set; }
public Employee(int empid, string FirstName, string LastName, string Email, string Mobile, string Address, int ROleID, string ROlename)
{
EmployeeID = empid;
firstName = FirstName;
lastName = LastName;
email = Email;
mobile = Mobile;
address = Address;
roleid = ROleID;
roleName = ROlename;
}
public Employee()
{
}
}
public class AddEmptoProject
{
public string ProjectName { get; set; }
public int EmployeeID { get; set; }
Project projecting = new Project();
Employee employing = new Employee();
public AddEmptoProject(string projectName, int employeeID)
{
this.ProjectName = projectName;
projectName = projecting.ProjectName;
this.EmployeeID = employeeID;
employeeID = employing.EmployeeID;
}
public AddEmptoProject()
{
}
}
public class AddingEmptoProject
{
public List<AddEmptoProject> AddingEmplist = new List<AddEmptoProject>();
public void addingemp(AddEmptoProject add)
{
AddingEmplist.Add(add);
}
}
//This part of code will be in main method
var PROJname = Console.ReadLine();
Console.WriteLine("Enter the id of employee to add into project");
int EMPID = Convert.ToInt32(Console.ReadLine());
AddEmptoProject ADDTOPROJ = new AddEmptoProject();
Project ADDTOPROJ1 = new Project();
Employee EMPIDD = new Employee();
if(PROJname.Equals(ADDTOPROJ1.ProjectName) && EMPID.Equals(EMPIDD.EmployeeID))
{
AddEmptoProject YADD = new AddEmptoProject(PROJname, EMPID);
AddingEmptoProject addition = new AddingEmptoProject();
addition.addingemp(YADD);
}
else
{
Console.WriteLine("Invalid Entry bro");
}
I am new to C#
I am trying to build a console application
In this everything seems to work fine but the if statement will does not execute
what is the error here ?
Is there any other way better than this ?
If possible can someone explain me the right way to add variables of different classes into List of another class
Related
My code returns userid, categoryid, locationid instead of the names to my list view.
I want to return names instead of id
//This is the get method in the service
public async Task<IEnumerable<JobViewModel>> GetAllJobsAsync()
{
var jobs = _appDbContext.Jobs
.Include(j => j.Category)
.Include(j => j.Location)
.Include(j => j.User)
.ToList();
return jobs.Select(job => new JobViewModel(job));
}
//Get method in the controller
public async Task<IActionResult> ListOfJobs()
{
var list = await _jobService.GetAllJobsAsync();
return Ok(list);
}
//This is the JobViewModel
public JobViewModel(JobClass job)
{
JobId = job.JobId;
JobTitle = job.JobTitle;
Description = job.Description;
Requirement = job.Requirement;
Experience = job.Experience;
Salary = job.Salary;
DatePosted = job.DatePosted;
Deadline = job.Deadline;
UserId = job.Id;
CategoryId = job.CategoryId;
LocationId = job.LocationId;
}
public Guid JobId { get; set; }
public string JobTitle { get; set; }
public string Description { get; set; }
public string Requirement { get; set; }
public string Experience { get; set; }
public int Salary { get; set; }
public DateTime DatePosted { get; set; }
public DateTime Deadline { get; set; }
public Guid UserId { get; set; }
public int LocationId { get; set; }
public int CategoryId { get; set; }
public IEnumerable<CategoryViewModel> Categories { get; set; }
public IEnumerable<LocationViewModel> Locations { get; set; }
}
EF Core : what can I do if I get this error in the project I am working on:
MySqlException: Duplicate entry '2' for key 'customers.IX_Customers_UserID'
UserID causes this error when it is present - I do not understand exactly what the error is, please help
public class Context : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Address> Addresses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//optionsBuilder.UseSqlite("Data Source = Shop.db");
//optionsBuilder.UseSqlServer(#"Data Source = (localdb)\v11.0; Initial Catalog=ShopDb; Integrated Security = SSPI;");
optionsBuilder.UseMySql(#"server=localhost;port=3306;database=ShopDb1;user=root;password=admin123;");
}
public Context()
{
Database.EnsureCreated();
}
}
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public Customer Customer { get; set; }
public List<Address> Addresses { get; set; }
}
public class Customer
{
public int ID { get; set; }
public int IdentifyNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public User User { get; set; }
public int UserID { get; set; }
}
public class Supplier
{
public int ID { get; set; }
public string Name { get; set; }
public string TaxNumber { get; set; }
}
public class Address
{
public int ID { get; set; }
public string FullName { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public User User { get; set; }
public int UserID { get; set; }
}
public class Product
{
public int ProductID { get; set; }
[MaxLength(100)]
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
public int CategoryID { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
[MaxLength(100)]
[Required]
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var db = new Context())
{
var customer = new Customer()
{
IdentifyNumber = 123,
FirstName = "Remzi",
LastName = "Balakishiyev",
User = db.Users.FirstOrDefault(x => x.ID == 2)
};
db.Customers.Add(customer);
db.SaveChanges();
}
Console.ReadLine();
}
static void InsertUsers()
{
var users = new List<User> {
new User() { UserName ="Remzi",Email = "remzi.balakisiyev#gmail.com"},
new User() { UserName ="Xezri",Email = "xezri.balakisiyev#gmail.com"},
new User() { UserName ="Nurane",Email = "nurane.tarverdiyeva#gmail.com"}
};
using (var db = new Context())
{
db.Users.AddRange(users);
db.SaveChanges();
}
}
static void InsertAddresses()
{
var addresses = new List<Address> {
new Address() { FullName = "Remzi Balakisiyev", Title = "Ev addressi", Body = "Masalli", UserID = 1 },
new Address() { FullName = "Remzi Balakisiyev", Title = "Ish addressi", Body = "Baki", UserID = 1 },
new Address() { FullName = "Xezri Balakisiyev", Title = "Ev addressi", Body = "Masalli", UserID = 2 },
new Address() { FullName = "Nurane Tarverdiyeva", Title = "Ev addressi", Body = "Naxcivvan", UserID = 3},
new Address() { FullName = "Rena Heyderova", Title = "Ev addressi", Body = "Xachmaz", UserID = 2 },
new Address() { FullName = "Memmed Bedelov", Title = "Ev addressi", Body = "Sumqayit", UserID = 1 }
};
using (var db = new Context())
{
db.Addresses.AddRange(addresses);
db.SaveChanges();
Console.WriteLine("Ishledi");
}
}
}
Your problem most probably is running on these lines of code:
var users = new List<User> {
new User() { UserName ="Remzi",Email = "remzi.balakisiyev#gmail.com"},
new User() { UserName ="Xezri",Email = "xezri.balakisiyev#gmail.com"},
new User() { UserName ="Nurane",Email = "nurane.tarverdiyeva#gmail.com"}
};
using (var db = new Context())
{
db.Users.AddRange(users);
db.SaveChanges(); // ERROR happening here, when trying to insert Users
}
The error is happening because you have put a unique PRIMARY Key constraint over the UserId column.
Try adding the following attribute over the ID, to fix the issue:
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
...
}
Another note, I think the UserId property redundant in your Customer class.
Please also check that if your Userā¶Customer relations are defined as one-to-many, then in your Customer class you have to define a collection of Users but not a single User:
public class Customer
{
...
public ICollection<User> Users { get; set; }
}
For more information check here.
internal class Person
{
[Key]
public int PersonId { get; set; }
[Required]
[StringLength(20)]
public string SurName { get; set; }
[Required]
[StringLength(20)]
public string LastName { get; set; }
[Required]
public DateTime BirthDate { get; set; }
public DateTime DeathDate { get; set; }
[Required]
public Gender gender { get; set; }
[Required]
[StringLength(20)]
public string Father { get; set; }
[Required]
[StringLength(20)]
public string Mother { get; set; }
public Person(string surName, string lastName, DateTime birthDate, Gender gender, string father, string mother)
{
SurName = surName;
LastName = lastName;
BirthDate = birthDate;
this.gender = gender;
Father = father;
Mother = mother;
}
I have dont have [required] by DeathDate, still it only crashes when there is no input for DeathDate.
The error shown in debugger when i want to add them to the database
Exception thrown: 'System.Data.SqlClient.SqlException' in
EntityFramework.dll
private void AddPersonButton_Click(object sender, RoutedEventArgs e)
{
if (DeathDateDatePicker.SelectedDate == null)
{
Person personsntDeath = new Person(
SurNameTextBlock.Text.Trim(),
LastNameTextBlock.Text.Trim(),
BirthDateDatePicker.SelectedDate.Value,
(Gender)SexComboBox.SelectedItem,
FatherTextBox.Text.Trim(),
MotherTextBox.Text.Trim());
personsntDeath.InsertIntoDB();
}
else
{
Person persons = new Person(
SurNameTextBlock.Text.Trim(),
LastNameTextBlock.Text.Trim(),
BirthDateDatePicker.SelectedDate.Value,
DeathDateDatePicker.SelectedDate.Value,
(Gender)SexComboBox.SelectedItem,
FatherTextBox.Text.Trim(),
MotherTextBox.Text.Trim());
persons.InsertIntoDB();
}
mainWindow.Content = new PageOverviewPersons(mainWindow);
}
If there is no input in DeathDatePicker i want it to be null in my database. It comes back with the value "{01/01/0001 00:00:00}"
public bool InsertPerson(Person persons)
{
using (DataBaseContext ctx = new DataBaseContext())
{
try
{
ctx.Persons.Add(persons);
ctx.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
}
I am trying to create a family tree program.
DateTime is a value type it can not be null unless you define it as nullable using ? operator
public DateTime? DeathDate { get; set; }
Try to change
public DateTime DeathDate { get; set; }
to
public DateTime? DeathDate { get; set; } //Nullable
And check if its got value by using DateTime?.HasValue property.
if (!DeathDateDatePicker.SelectedDate.HasValue)
{
// Your code here
}
I have a WPF C# desktop app and I am using SQLite.
I have this model:
using SQLite;
[Table("Customer")]
public class Customer
{
[AutoIncrement]
[PrimaryKey]
public int CustomerId { get; set; }
public string CustomerRef { get; set; }
public string SName { get; set; }
public string FName { get; set; }
public string ContactNo { get; set; }
public string Email { get; set; }
public string Add1 { get; set; }
public string Add2 { get; set; }
public string Add3 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string PCode { get; set; }
public string Country { get; set; }
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if (!string.IsNullOrEmpty( Add1))
{
sb.AppendLine(Add1.Trim());
}
if (!string.IsNullOrEmpty(Add2))
{
sb.AppendLine(Add2.Trim());
}
if (!string.IsNullOrEmpty(Add3))
{
sb.AppendLine(Add3.Trim());
}
if (!string.IsNullOrEmpty(Town))
{
sb.AppendLine(Town.Trim());
}
if (!string.IsNullOrEmpty(County))
{
sb.AppendLine(County.Trim());
}
if (!string.IsNullOrEmpty(PCode))
{
sb.AppendLine(PCode.Trim());
}
if (!string.IsNullOrEmpty(Country))
{
sb.AppendLine(Country.Trim());
}
return sb.ToString();
}
}
I add records to it - no problems. I try to update and I get a cannot update as there is no primary key.
This is the code:
var query = DB.Connector.Table<InformedWorkerModel.Customer>().Where(d => d.CustomerRef == customer.CustomerRef).FirstOrDefault();
if (query != null)
{
query.Add1 = customer.Add1;
query.Add2 = customer.Add2;
query.Add3 = customer.Add3;
query.Town = customer.Town;
query.County = customer.County;
query.Country = customer.Country;
query.PCode = customer.PCode;
query.ContactNo = customer.ContactNo;
query.Email = customer.Email;
query.FName = customer.FName;
query.SName = customer.SName;
DB.Connector.Update(query);
return query;
}
It breaks on the driver code here and as you can see the quick watch shows no Primary Key on the field:
This is the screenshot where I initially created the database.
Any ideas please?
thanks
Hope you are doing good !
its seems like your data schema and your model is not mapped properly.
you can use attribute to mapped.
[Table("Customer")]
class Customer
{
[PrimaryKey, AutoIncrement]
[Column(Name = "CustomerId")]
public int CustomerId { get; set; }
.......
}
Regards MK
I'm having the strangest problem and I know it's because I'm missing something obvious because this set up works fine when I save data and even pull it down.
My app is set up like so ....
WebUI depends on Business Layer .. Business Layer depends on Data Layer (which is where I'm actually pulling the data). The Business Layer does all the "work".
This is where everything dies (Null Exception, Object Reference not set) as soon as I assign something to userInfo.userData.avatarFilepath (which is not null).
namespace pgl.businesslayer
{
public class userCtx
{
private pgl.datalayer.Concrete.EFDbContext context = new pgl.datalayer.Concrete.EFDbContext();
private pgl.datalayer.Concrete.EFUserContext userContext = new pgl.datalayer.Concrete.EFUserContext();
private pgl.datalayer.Concrete.EFDbCompany companyContext = new pgl.datalayer.Concrete.EFDbCompany();
public ViewModels.UserInfo getUserById(int userId)
{
ViewModels.UserInfo userInfo = new ViewModels.UserInfo();
pgl.datalayer.Dtos.pglUserDTO userDL = userContext.getUserByUserId(userId);
userInfo.userData.avatarFilepath = userDL.avatarFilepath;
userInfo.userData.createdBy = userDL.createdBy;
userInfo.userData.createdDate = userDL.createdDate;
userInfo.userData.email = userDL.email;
userInfo.userData.firstName = userDL.firstName;
userInfo.userData.lastName = userDL.lastName;
etc...
}
ViewModels.UserInfo looks like this...
namespace pgl.businesslayer.ViewModels
{
public class UserInfo
{
// user info
public pgl.businesslayer.Dto.pglUser userData { get; set; }
// salon info
public List<pglSalon> salonsData { get; set; }
// company info
public pglCompany companyData { get; set; }
}
pglUser in the business layer looks like this and is just a POCO
namespace pgl.businesslayer.Dto
{
public class pglUser
{
public int userId { get; set; }
public int companyId { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string username { get; set; }
public byte[] passwordSalt { get; set; }
public byte[] passwordKey { get; set; }
public DateTime createdDate { get; set; }
public int createdBy { get; set; }
public bool passwordResetRequired { get; set; }
public string passwordHash { get; set; }
public string tempPassword { get; set; }
public string userType { get; set; }
public string avatarFilepath { get; set; }
public string timeZone { get; set; }
}
}
And in userContext this is how I am pulling the user data...
public pgl.datalayer.Dtos.pglUserDTO getUserByUserId(int userId)
{
var getUser = (from u in context.pglUser
select new pgl.datalayer.Dtos.pglUserDTO
{
username = u.username,
companyId = u.companyId,
userId = u.userId,
userType = u.userType,
firstName = u.firstName,
lastName = u.lastName,
email = u.email,
createdDate = u.createdDate,
createdBy = u.createdBy,
passwordResetRequired = u.passwordResetRequired,
tempPassword = u.tempPassword,
avatarFilepath = u.avatarFilepath,
timeZone = u.timeZone
}).Where(u => u.userId == userId).FirstOrDefault();
return getUser;
}
pgl.datalayer.Dtos.pglUserDTO looks like this...
namespace pgl.datalayer.Dtos
{
public class pglUserDTO
{
public int userId { get; set; }
public int companyId { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string username { get; set; }
public byte[] passwordSalt { get; set; }
public byte[] passwordKey { get; set; }
public DateTime createdDate { get; set; }
public int createdBy { get; set; }
public bool passwordResetRequired { get; set; }
public string passwordHash { get; set; }
public string tempPassword { get; set; }
public string userType { get; set; }
public string avatarFilepath { get; set; }
public string timeZone { get; set; }
}
}
Even if I assign userInfo.userData.avatarFilepath = "WHATUP!!!" it throws the same error. This has got to be something stupid and simple. I can save data with no problem and when I debug I can see that it is actually pulling the correct user ID and it's associated data. It's just that pgl.businesslayer.ViewModels.UserInfo seems to be un-instantiated. I'm at a loss. I can provide more info... and keep in mind I'm kind of at my wits end so I tried doing weird things like adding (probably) unnecessary DTOs. Any ideas?
You don't appear to be creating the userData object anywhere. When you create a new instance of UserInfo, or in its constructor, try adding:
userData = new pgl.businesslayer.Dto.pglUser();
Or alternatively:
ViewModels.UserInfo userInfo = new ViewModels.UserInfo();
pgl.datalayer.Dtos.pglUserDTO userDL = userContext.getUserByUserId(userId);
userInfo.userData = new pgl.businesslayer.Dto.pglUser {
avatarFilepath = userDL.avatarFilepath,
createdBy = userDL.createdBy,
createdDate = userDL.createdDate,
email = userDL.email,
firstName = userDL.firstName,
lastName = userDL.lastName
};
If you always want to initialise UserInfo with an empty userData member, you could include the creation within the constructor:
namespace pgl.businesslayer.ViewModels
{
public class UserInfo
{
// Default constructor
public UserInfo()
{
userData = new pgl.businesslayer.Dto.pglUser();
}
// user info
public pgl.businesslayer.Dto.pglUser userData { get; set; }
// salon info
public List<pglSalon> salonsData { get; set; }
// company info
public pglCompany companyData { get; set; }
}
}