Saving data in the database using Entity Framework - c#

I am trying to save data in the database using Entity Framework and this code, but I keep getting this error:
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at GDEProject.Pages.Profile.Update_Click(Object sender, EventArgs e) in
C:\Users\RATAU\Documents\Projects\GDEProject\GDEProject\GDEProject\Pages\Profile.aspx.cs:line 48
This is the code I am using:
public partial class Profile : System.Web.UI.Page
{
Entities2 db = new Entities2();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Update_Click(object sender, EventArgs e)
{
if (ModelState.IsValid)
{
try
{
PROFILE user = new PROFILE();
user.IdNumber = IdNumber.Text;
user.PersalNumber = ParselNumber.Text;
user.Title = Title.Text;
user.Initials = Initial.Text;
user.Name = FirstName.Text;
user.Surname = LastName.Text;
user.Age = Age.Text;
user.Race = Race.Text;
user.EmailAddress = Email.Text;
user.CellPhone = Phonenumber.Text;
user.TelephoneNumber = Telephone.Text;
user.Nationality = dropNationality.SelectedValue.ToString();
user.Gender = dropGender.SelectedValue.ToString();
user.Disability = Disability.SelectedValue.ToString();
user.DisabilityType = DisabilityType.Text;
db.PROFILEs.Add(user);
db.SaveChanges();
ErrorMessage.Text = "saved";
}
catch (Exception ee)
{
ErrorMessage.Text = ("error" + ee);
}
}
else
{
ErrorMessage.Text="modelstate failed";
}
}
the class of profile is as follows:
public partial class PROFILE
{
public string Nationality { get; set; }
public string IdNumber { get; set; }
public string PersalNumber { get; set; }
public string Title { get; set; }
public string Initials { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
public string Race { get; set; }
public string Language { get; set; }
public string EmailAddress { get; set; }
public string CellPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Disability { get; set; }
public string DisabilityType { get; set; }
public string Message { get; set; }
}
}
Please assist

Related

Link Column In Datagridview C#

How can I set PDF and Word column to link column(Please see the photo below)?
The code to get data from the database:
public IQueryable<Document> GetAllDocuments()
{
//Somethings
}
public List<DocumentForIndexViewModel> GetAllDocumentsForIndexViewModel()
{
List<Document> documents = GetAllDocuments().ToList();
var documentsForIndexViewModel = new List<DocumentForIndexViewModel>();
foreach (var document in documents)
{
var documentForIndexViewModel = new DocumentForIndexViewModel
{
Id = document.Id,
PDFFileName = document.PDFFiles.Last().PDFFileName,
WordFileName = document.WordFiles.Last().WordFileName,
IsDelete = document.Deletes.Last().IsDelete,
CreateDate = document.ActivityTimes.First().Time.ToShamsi(),
DocName = document.DocumentNames.Last().Name,
Producer = document.ProducerNames.Last().Name,
Approver = document.Approvers.Last().Name,
Type = document.Type.Name,
};
EditNumber editNumber = document.EditNumbers.LastOrDefault();
if (editNumber != null)
{
documentForIndexViewModel.LastEditNumber = editNumber.Number;
}
EditDate editDate = document.EditDates.LastOrDefault();
if (editDate != null)
{
documentForIndexViewModel.LastEditDate = editDate.Date.ToShamsi();
}
Review review = document.Reviews.LastOrDefault();
if (review != null)
{
documentForIndexViewModel.LastReviewDate = review.ReviewDate.ToShamsi();
}
documentsForIndexViewModel.Add(documentForIndexViewModel);
}
return documentsForIndexViewModel;
}
DocumentForIndexViewModel:
public class DocumentForIndexViewModel
{
public int Id { get; set; }
[DisplayName("نام سند")]
public string DocName { get; set; }
[DisplayName("نوع")]
public string Type { get; set; }
[DisplayName("فرمت")]
public string Format { get; set; }
[DisplayName("تاریخ ساخت")]
public string CreateDate { get; set; }
[DisplayName("آخرین شماره ویرایش")]
public int? LastEditNumber { get; set; }
[DisplayName("آخرین تاریخ ویرایش")]
public string? LastEditDate { get; set; }
[DisplayName("آخرین بازبینی")]
public string? LastReviewDate { get; set; }
[DisplayName("PDF")]
public string PDFFileName { get; set; }
[DisplayName("تهیه کننده")]
public string Producer { get; set; }
[DisplayName("تصویب کننده")]
public string Approver { get; set; }
[DisplayName("امحا")]
public bool IsDelete { get; set; }
[DisplayName("Word")]
public string WordFileName { get; set; }
}
the code to get data from GetAllDocumentsForIndexViewModel() method in index form:
private void IndexForm_Load(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
MyDataGridView.DataSource = null;
using (UnitOfWork db = new UnitOfWork())
{
var documents = db.DocumentRepository.GetAllDocumentsForIndexViewModel();
MyDataGridView.DataSource = documents;
MyDataGridView.Columns[0].Visible = false;
MyDataGridView.Columns["LastEditDate"].Width = 170;
MyDataGridView.Columns["LastEditNumber"].Width = 170;
}
}
Thankyou

SQLite Xamarin/C# inserting data

I am developing an application. I have connected my project to SQLIte, now I am trying to add an advert, which I am failing to do.
my SQLInterface
public interface ISQLiteInterface
{
SQLiteConnection GetSQLiteConnection();
}
my Droid SQL
public class SQLiteDb : ISQLiteInterface
{
public SQLiteDb()
{
}
public SQLiteConnection GetSQLiteConnection()
{
var fileName = "Mydatabase.db";
var dbpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(dbpath, fileName);
var connection = new SQLiteConnection(path);
return connection;
}
}
}
my model
public class AdLogEntry
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string SellerName { get; set; }
public string Name { get; set; }
public List<Picture> Pictures { get; set; }
public List<Video> Videos { get; set; }
public string Image { get; set; }
public string Video { get; set; }
public string Description { get; set; }
public string Price { get; set; }
public string LoadedDate { get; set; }
public string Location { get; set; }
public int Age { get; set; }
}
public class Picture
{
public string Id { get; set; }
public string Url { get; set; }
public byte[] Image { get; set; }
}
public class Video
{
public string Id { get; set; }
public string Url { get; set; }
public byte[] ImageVideo { get; set; }
}
}
this is my task
private async void NextStep_Clicked(object sender, EventArgs e)
{
await SaveAdLog();
}
private async Task SaveAdLog()
{
if (string.IsNullOrWhiteSpace(NameEntry.Text) || (string.IsNullOrWhiteSpace(PriceEntry.Text) || (string.IsNullOrWhiteSpace(LocationEntry.Text))))
{
await DisplayAlert("error", "fill all entries", "OK");
}
else {
var adLogEntry = new AdLogEntry
{
Location = LocationEntry.Text,
Price = PriceEntry.Text,
Name = NameEntry.Text,
};
var result = _adService.CreateAddLogEntry(adLogEntry); //ok
if (result == null)
{
await DisplayAlert("Gratulace", "", "OK");
App.Current.MainPage = new AppShell();
}
};
}
this is my advertservice
class AdService
{
private SQLiteConnection _conn;
public AdService()
{
_conn = DependencyService.Get<Helpers.ISQLiteInterface>().GetSQLiteConnection();
_conn.CreateTable<AdLogEntry>();
}
public string CreateAddLogEntry(AdLogEntry adLogEntry)
{
var detail = _conn.Table<AdLogEntry>();
var d1 = detail.Connection.Insert(adLogEntry);
return "Thank you";
}
}
}
Once I press the button nothing happens. When I try to debug it i get 'Object reference not set to an instance of an object.'
Edit.
This app is supposed to be something like LetItGo so all values should be able to repeat
I have ISQLite interface implemented.
According to your error message, I can not see where you instantiate a new instance of the AdService class.
So please try to add the following code before you call _adService.CreateAddLogEntry() method.
_adService = new AdService();
i think SQLite can't process this properties in your model
List< Picture > and
List< Video >
public List<Picture> Pictures { get; set; }
public List<Video> Videos { get; set; }
I suggest that you change the property to string and serialize the data before saving

Using Dapper in method context to return multiple lists

I have a vendor class like this:
public class Vendor: DataAccess
{
//properties
public int VEND_ID;
public string VEND_NAME { get; set; }
public string VEND_ADDRESS { get; set; }
public string VEND_PHONE { get; set; }
public string VEND_WEBSITE { get; set; }
public string NOTES { get; set; }
public static string ErrorMessage { get; set; }
//Constructors
public Vendor(string name,string address,string phone,string website,string notes)
{
VEND_NAME = name;
VEND_ADDRESS = address;
VEND_PHONE = phone;
VEND_WEBSITE = website;
NOTES = notes;
}
public Vendor(string name)
{
VEND_NAME = name;
}
public Vendor() { }
)
I have an Orders Class like this:
public class Order: DataAccess
{
//properties
public int ORDER_ID { get; set; }
public Vendor VENDOR_ID { get; set; }
public string ENTRY_DATE { get; set; }
public string ORDER_NO { get; set; }
public string TOTAL_COST { get; set; }
public string STATUS { get; set; }
public string NOTES { get; set; }
public string ATTACH_ID { get; set; }
public static string ErrorMessage { get; set; }
//constructors
//public Order(string )
}
My Data Access Class has the following method:
public Tuple<List<Vendor>, List<Order>> GetVendorByName(string name)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("TESTDB")))
{
using (var multi = connection.QueryMultiple("dbo.GetVendor_ByName", new { VEND_NAME = name }))
{
List<Vendor> vd=new List<Vendor>();
vd.Add(multi.Read<Vendor>().First());
List<Order> od = new List<Order>();
od.Add(multi.Read<Order>().Single());
var output = Tuple.Create(vd, od);
return output;
}
//var output = connection.QueryMultiple<Vendor>("dbo.GetVendor_ByName", new { VEND_NAME = name }).ToList();
}
}
The main class uses it like this:
List<Vendor> vendor = new List<Vendor>();
private void _search_Click(object sender, EventArgs e)
{
Vendor db = new Vendor(cb_vendor.Text);
vendor=db.GetVendorByName(cb_vendor.Text);//This is where the error is pointed at
//dgv_data.Refresh();
dgv_data.DataSource = vendor;
}
I am trying to get the data from the SQL procedure to show in the DataGridView (dgv_data). There is a one to many relation between Vendor and Order. I want to get all the Orders for whatever Vendor Name is selected
I know the issue is that I am returning List. I tried using Tuples but no joy, it gives me an error about implicit conversions. Any idea how to do what I am trying to accomplish?
Error CS0029 Cannot implicitly convert type
'System.Tuple,
System.Collections.Generic.List>' to
'System.Collections.Generic.List' PurchApp
Update1:
The stored procedure is like this:
ALTER proc [dbo].[GetVendor_ByName]
(
#VEND_NAME varchar(100)
)
as
Select Distinct a.VEND_NAME,b.* from dbo.Purch_Vendor a left join purch_order b on a.vendor_id=b.vendor_id where a.Vend_Name=#VEND_NAME
Try this. It maps orders to the vendor on name. I have added a property for List of Orders to the Vendor
public class Vendor : DataAccess
{
//properties
public int VEND_ID;
public string VEND_NAME { get; set; }
public string VEND_ADDRESS { get; set; }
public string VEND_PHONE { get; set; }
public string VEND_WEBSITE { get; set; }
public string NOTES { get; set; }
public List<Order> ORDERS { get; set; }
public static string ErrorMessage { get; set; }
//Constructors
public Vendor(string name, string address, string phone, string website, string
notes)
{
VEND_NAME = name;
VEND_ADDRESS = address;
VEND_PHONE = phone;
VEND_WEBSITE = website;
NOTES = notes;
}
public Vendor(string name)
{
VEND_NAME = name;
}
public Vendor() { }
}
public class Order : DataAccess
{
//properties
public int ORDER_ID { get; set; }
public Vendor VENDOR_ID { get; set; }
public string ENTRY_DATE { get; set; }
public string ORDER_NO { get; set; }
public string TOTAL_COST { get; set; }
public string STATUS { get; set; }
public string NOTES { get; set; }
public string ATTACH_ID { get; set; }
public static string ErrorMessage { get; set; }
//constructors
//public Order(string )
}
public Vendor GetVendorByName(string name)
{
using (IDbConnection connection = new
SqlConnection(Helper.CnnVal("TESTDB")))
{
var dict = new Dictionary<string, Vendor>();
var vendors = connection.Query<Vendor, Order, Vendor>
("dbo.GetVendor_ByName", (a, b) => Mapper(a, b, dict), new {
VEND_NAME = name }, splitOn: "ORDER_ID");
return dict.Values.FirstOrDefault()
}
}
public Vendor Mapper(Vendor vendor, Order order, Dictionary<string, Vendor> dict)
{
if (!dict.ContainsKey(vendor.VEND_NAME))
{
vendor.ORDERS = new List<Order>();
dict.Add(vendor.VEND_NAME, vendor);
}
var currentVendor = dict[vendor.VEND_NAME];
currentVendor.ORDERS.Add(order);
return currentVendor;
}

A referential integrity constraint violation occurred. When Updating EF

I can't seem to be able to update a model with foreignKey constraint getting this error :
Additional information: A referential integrity constraint violation
occurred: The property value(s) of 'Country.Id' on one end of a
relationship do not match the property value(s) of 'Setting.CountryId'
on the other end.
Setting Model
namespace Domain
{
public class Setting : BaseModel
{
public string Address { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Website { get; set; }
public string Slogan { get; set; }
public byte[] Logo { get; set; }
public string City { get; set; }
public string RegistrationNo { get; set; }
[ForeignKey("State")]
public int StateId { get; set; }
public State State { get; set; }
[ForeignKey("Country")]
public int CountryId { get; set; }
public Country Country { get; set; }
public string IsDefault { get; set; }
}
}
State Model
namespace Domain
{
public class State :BaseModel
{
public string Name { get; set; }
}
}
Country Model
namespace Domain
{
public class Country : BaseModel
{
public string Name { get; set; }
}
}
Repository to Get and Update Setting
public Setting GetSetting()
{
try
{
return _db.Settings.Include("Country").Include("State").First();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public Setting UpdateSetting(Setting setting)
{
try
{
_db.Settings.Attach(setting);
_db.Entry(setting).State = EntityState.Modified;
_db.SaveChanges();
return setting;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Note I am Using WCF Proxy
Button Click Event
private void btnSave_Click(object sender, EventArgs e)
{
//MessageBox.Show(Convert.ToInt16(cmbState.EditValue).ToString());
//return;
if (dxValidationProvider1.Validate())
{
if (picLogo.Image == null)
{
XtraMessageBox.Show("Upload Logo");
}
else
{
var setting = proxy.GetSetting();
//MessageBox.Show(cmbState.EditValue.ToString()); return;
setting.HotelName = txtHotelName.Text;
setting.Address = txtAddress.Text;
setting.Email = txtEmail.Text;
setting.Phone = txtPhone.Text;
setting.Website = txtWebsite.Text;
setting.Slogan = txtSlogan.Text;
setting.City = txtCity.Text;
setting.CountryId = Convert.ToInt16(cmbCounty.EditValue);
setting.StateId = Convert.ToInt16(cmbState.EditValue));
setting.Logo = picLogo.Image.ToByteArray();
var s = proxy.UpdateSetting(setting);
MessageBox.Show(#"Updated");
}
}
else
{
MessageBox.Show("Please fill the required fields");
}
}
I just removed the Include statment from the GetSetting function and everything updated. This solved my problem
public Setting GetSetting()
{
try
{
return _db.Settings.First();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}

Model doesn't accept its value

This code doesn't accept the values I give with the user's department data. If i replace user.Department.ID with just a simple int variable, it works fine. This is also the problem with user.Department.Code and user.Department.Title. I don't know what's the problem. Is it in my models?
This is the code. The system queries for the user data. I believe that the query is fine. I'm using a connection string with MS Access btw.
try
{
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
UserModel user = new UserModel();
if (!reader.IsDBNull(0))
{
user.Id = reader.GetInt32(0);
}
if (!reader.IsDBNull(1))
{
user.Department.Id = reader.GetInt32(1);
}
if (!reader.IsDBNull(2))
{
user.Department.Code = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
user.Department.Title = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
user.FamilyName = reader.GetString(4);
}
if (!reader.IsDBNull(5))
{
user.GivenName = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
user.MiddleName = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
user.NameSuffix = reader.GetString(7);
}
if (!reader.IsDBNull(8))
{
user.Type = reader.GetString(8);
}
CurrentUser = user;
CanLogin = true;
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception Error");
}
Here is my Usermodel...
class UserModel
{
public int Id { get; set; }
public DepartmentModel Department { get; set; }
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
public string NameSuffix { get; set; }
public string Type { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName(bool isFamilyNameFirst)
{
StringBuilder fullname = new StringBuilder();
if(isFamilyNameFirst)
{
fullname.Append(FamilyName).Append(", ").Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(NameSuffix);
}
else
{
fullname.Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(FamilyName).Append(" ").Append(NameSuffix);
}
return fullname.ToString();
}
}
And my Department Model..
class DepartmentModel
{
public int Id { get; set; }
public InstitutionModel Institution { get; set; }
public string Code { get; set; }
public string Title { get; set; }
}
The Department property never initialize any where, you an do it in user constructor:
class UserModel
{
public UserModel()
{
this.Department = new DepartmentModel();
}
public int Id { get; set; }
public DepartmentModel Department { get; set; }
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
public string NameSuffix { get; set; }
public string Type { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName(bool isFamilyNameFirst)
{
StringBuilder fullname = new StringBuilder();
if(isFamilyNameFirst)
{
fullname.Append(FamilyName).Append(", ").Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(NameSuffix);
}
else
{
fullname.Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(FamilyName).Append(" ").Append(NameSuffix);
}
return fullname.ToString();
}
}
Or
UserModel user = new UserModel() {Department = new DepartmentModel()};

Categories