how update two tables from Edit View ASP.NET MVC? - c#

I am trying to update data from two tables; products and inventory. The main key of the table products is cod_prod, which is the barcode of a product. This is the relationship with the products table and the other. The update is carried out for all the fields, but in the database administrator, the cod_prod field in the inventory table is not updated, it only becomes null, in the products table the update is carried out, the reg_date field, which is a field in the inventory table is also updated. Only the cod_prod field on the inventory table is not updated and I don't know why.
ViewModel:
public class products
{
[Display(Name = "Name")]
public string name { get; set; }
[Key]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
[Display(Name = "Register Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? reg_date { get; set; }
}
Controller:
[HttpGet]
public ActionResult prodEdit(int id)
{
using (inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
var u = dc.products.Where(a => a.id == id).FirstOrDefault();
if (u != null)
{
var pm = new products
{
name = u.name,
cod_prod = u.cod_prod,
reg_date = u.reg_date
};
var b = dc.inventory.Where(x => x.cod_prod == pm.cod_prod).FirstOrDefault();
u.cod_prod = b.cod_prod;
return View(u);
}
return Content("Invalid Request");
}
}
[HttpPost]
public ActionResult prodEdit(products prod)
{
using (inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
var u = dc.products.Where(a => a.id == prod.id).FirstOrDefault();
var b = dc.inventory.Where(x => x.cod_prod == prod.cod_prod).FirstOrDefault();
inventory bod = new inventory()
{
cod_prod = prod.cod_prod,
reg_date = prod.reg_date
};
dc.inventory.Remove(b);
dc.inventory.Add(bod);
dc.products.Remove(u);
dc.products.Add(prod);
dc.SaveChanges();
return RedirectToAction("prodList", "products");
}
}
Any suggestion is appreciated.
UPDATE:
Model for products:
public partial class products
{
[Display(Name = "Name")]
public string name { get; set; }
[Key]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
}
Model for inventory:
public partial class inventory
{
[Key]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
[Display(Name = "Register Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? reg_date { get; set; }
}

Suppose you have one to one relation between Products and Inventory tables, your models will look like this in EF:
Products model
public class Products
{
[Display(Name = "Name")]
public string name { get; set; }
[Key]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
public virtual Inventory Inventory {get;set;}
}
Inventory model
public class Inventory
{
[Key, ForeignKey("Products")]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
[Display(Name = "Register Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? reg_date { get; set; }
public virtual Products Products {get;set;}
}
Once relation is configured, you can simply do this in the POST method to update product and inventory:
[HttpPost]
public ActionResult prodEdit(Products prod)
{
using (inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
var product = dc.products.Where(a => a.id == prod.id).FirstOrDefault();
var inventory = product.Inventory;
inventory.cod_prod = prod.cod_prod;
inventory.reg_date = prod.reg_date;
dc.SaveChanges();
return RedirectToAction("prodList", "products");
}
}
You can read more about how to configure EF relation here.

If the same thing happens to someone, this is what I wrote to resolve it, the controller has two post methods, the first removes the fields that were changed, save data base and send the products and inventory objects to the second method, there, adds the new data of the models and save. I had to do this way because the removal of the PK on the products table causes the null thing.
Controller:
[HttpPost]
public ActionResult prodEdit(products prod)
{
using(inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
var u = dc.products.Where(a => a.id == prod.id).FirstOrDefault();
if(u != null)
{
var pm = new products
{
prod_name = prod.prod_name,
cod_prod = prod.cod_prod,
fecha_ingreso = prod.fecha_ingreso
};
var b = dc.bodega.Where(x => x.cod_prod == u.cod_prod).FirstOrDefault();
if (b != null)
{
inventory inv = new inventory()
{
reg_date = pm.fecha_ingreso,
cod_prod = pm.codigo_prod
};
if (inv.cod_prod != null)
{
dc.inventory.Remove(b);
dc.products.Remove(u);
dc.SaveChanges();
prodEdit2(prod, bod);
}
}
}
return RedirectToAction("prodList", "products");
}
}
[HttpPost]
public ActionResult prodEdit2(products p, inventory i)
{
using (inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
dc.products.Add(p);
dc.inventory.Add(i);
dc.SaveChanges();
return RedirectToAction("prodList", "products");
}
}

Related

How to automap the property with same class?

I want to map all properties from product to result.
I use the route to pass the model, then follow the tutorial to map all properties.
But I want to make my code more flexible.
So I try both to direct pass product to result and use AutoMapper.
But either doesn’t work.
I have print changeTracker. When I use like result.Name = product.Name; ETC, it can track the change. But The method I try to use doesn’t work;
Original
public IActionResult Edit(TempProducts product)
{
if (this.ModelState.IsValid)
{
var result = (from s in _db.Product where s.ID == product.ID select s).FirstOrDefault();
result.Name = product.Name;
result.Description = product.Description;
result.PublishDate = product.PublishDate;
result.CategoryId = product.CategoryId;
result.Price = product.Price;
result.DefaultImageId = product.DefaultImageId;
result.Quantity = product.Quantity;
result.Status = product.Status;
_db.ChangeTracker.DetectChanges();
Console.WriteLine(_db.ChangeTracker.DebugView.LongView);
_db.SaveChanges();
return RedirectToAction(nameof(Pass2.index));
}
else
{
return View(product);
}
}
Direct pass
public IActionResult Edit(TempProducts product)
{
if (this.ModelState.IsValid)
{
var result = (from s in _db.Product where s.ID == product.ID select s).FirstOrDefault();
result = product;
_db.ChangeTracker.DetectChanges();
Console.WriteLine(_db.ChangeTracker.DebugView.LongView);
_db.SaveChanges();
return RedirectToAction(nameof(Pass2.index));
}
else
{
return View(product);
}
}
Use AutoMapper
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(TempProducts product)
{
if (this.ModelState.IsValid)
{
var config = new MapperConfiguration(c =>
{
c.CreateMap<TempProducts, TempProducts>();
});
IMapper mapper = config.CreateMapper();
#nullable disable
var result = (from s in _db.Product where s.ID == product.ID select s).FirstOrDefault();
result = mapper.Map<TempProducts,TempProducts>(product);
_db.ChangeTracker.DetectChanges();
Console.WriteLine(_db.ChangeTracker.DebugView.LongView);
_db.SaveChanges();
return RedirectToAction(nameof(Pass2.index));
}
else
{
return View(product);
}
}
Edit: TempProducts
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace forLearn.Models.RouteTest
{
public partial class TempProducts
{
public uint ID { get; set; }
public string Name { get; set; }=null!;
public string Description { get; set; }=null!;
[Range(0, 999)]
public int CategoryId { get; set; }
[Range(0, 999.99)]
public int Price { get; set; }
[DataType(DataType.Date)]
public DateTime PublishDate { get; set; }
public bool Status { get; set; }
public int DefaultImageId { get; set; }
[Range(0, 999)]
public int Quantity { get; set; }
}
}
I have found the answer.
Just add this below the result.
_db.Entry(result).CurrentValues.SetValues(product);

Argument 1: cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.List'

I'm learning Asp.net Core and building a simple web with CRUD operations, SQL server and using Entity Framework.
When I try to build a sorting method I git this error in this line at parameter employees
return View(this.SortEmployees(employees, SortField, CurrentSortField, SortDirection));
and that's the error:
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'System.Collections.Generic.List<EmployeesApp.Models.Employee>' to 'System.Collections.Generic.List<EmployeesApp.Controllers.Employee>' EmployeesApp
that's my Model:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EmployeesApp.Models
{
[Table("Employee", Schema ="dbo")]
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name ="Employee ID")]
public int EmployeeId { get; set; }
[Required]
[Column(TypeName ="varchar(5)")]
[MaxLength(5)]
[Display(Name ="Employee Number")]
public string EmployeeNumber { get; set; }
[Required]
[Column(TypeName = "varchar(150)")]
[MaxLength(100)]
[Display(Name = "Employee Name")]
public string EmployeeName { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name ="Date of Birth")]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}")]
public DateTime DOB { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Hiring Date")]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}")]
public DateTime HiringDate { get; set; }
[Required]
[Column(TypeName ="decimal(12,2)")]
[Display(Name ="Gross Salary")]
public decimal GrossSalary { get; set; }
[Required]
[Column(TypeName = "decimal(12,2)")]
[Display(Name = "Net Salary")]
public decimal NetSalary { get; set; }
[ForeignKey("Department")]
[Required]
public int DepartmentId { get; set; }
[Display(Name = "Department")]
[NotMapped]
public string DepartmentName { get; set; }
public virtual Department Department { get; set; }
}
}
and that's my COntroller:
namespace EmployeesApp.Controllers
{
public enum SortDirection
{
Ascending,
Descending
}
public class Employee : Controller
{
HRDatabaseContext dbContext = new HRDatabaseContext();
public IActionResult Index(string SortField, string CurrentSortField, SortDirection SortDirection)
{
var employees = GetEmployees();
return View(this.SortEmployees(employees, SortField, CurrentSortField, SortDirection));
}
private List<Models.Employee> GetEmployees()
{
return (from Employee in dbContext.Employees
join Department in dbContext.Departments on Employee.DepartmentId equals Department.DepartmentId
select new Models.Employee
{
EmployeeId = Employee.EmployeeId,
EmployeeName = Employee.EmployeeName,
DOB = Employee.DOB,
HiringDate = Employee.HiringDate,
GrossSalary = Employee.GrossSalary,
NetSalary = Employee.NetSalary,
DepartmentId = Employee.DepartmentId,
DepartmentName = Department.DepartmentName
}).ToList();
}
public IActionResult Add()
{
ViewBag.Department = this.dbContext.Departments.ToList();
return View();
}
[HttpPost]
public IActionResult Add(Models.Employee model)
{
ModelState.Remove("EmployeeID");
ModelState.Remove("Department");
ModelState.Remove("DepartmentName");
if (ModelState.IsValid)
{
dbContext.Employees.Add(model);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Department = dbContext.Departments.ToList();
return View("Add", model);
}
public IActionResult Edit(int ID)
{
HRDatabaseContext dbContext1 = dbContext;
Models.Employee data = dbContext1.Employees.Where(e => e.EmployeeId == ID).FirstOrDefault();
ViewBag.Department = this.dbContext.Departments.ToList();
return View("Add", data);
}
[HttpPost]
public IActionResult Edit(Models.Employee model)
{
ModelState.Remove("EmployeeID");
ModelState.Remove("Department");
ModelState.Remove("DepartmentName");
if (ModelState.IsValid)
{
dbContext.Employees.Update(model);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Department = dbContext.Departments.ToList();
return View();
}
public IActionResult Delete(int ID)
{
Models.Employee data = this.dbContext.Employees.Where(e => e.EmployeeId == ID).FirstOrDefault();
if (data != null)
{
dbContext.Employees.Remove(data);
dbContext.SaveChanges();
}
return RedirectToAction("Index");
}
private List<Employee> SortEmployees(List<Employee> employees, String sortField, string currentSortField, SortDirection sortDirection)
{
if (string.IsNullOrEmpty(sortField))
{
ViewBag.SortField = "EmployeeNumber";
ViewBag.SortField = SortDirection.Ascending;
}
else
{
if (currentSortField == sortField)
{
ViewBag.SortDirection = sortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
}
else
ViewBag.SortDirection = sortDirection == SortDirection.Ascending;
ViewBag.SortField = sortField;
}
//* create the sorting proccess
var propertyInfo = typeof(Employee).GetProperty(ViewBag.SortField);
if (ViewBag.SortDirection == SortDirection.Ascending)
{
employees = employees.OrderBy(e => propertyInfo.GetValue(e, null)).ToList();
}
else
{
employees = employees.OrderByDescending(e => propertyInfo.GetValue(e, null)).ToList();
}
return employees;
}
}
}
Your SortEmployees method in your controller takes a List<Employee> which in this context is a Controllers.Employee and not a Models.Employee as you suspect.
The best solution in this case is to rename your Controller to EmployeeController to follow the ASP.NET convention. In ASP.NET controllers are always named [Name]Controller.
private List<Employee> SortEmployees(List<Employee> employees, String sortField, string currentSortField, SortDirection sortDirection)
{
The issue relates the above SortEmployees method, its parameter and return data using the EmployeesApp.Controllers.Employee model, istead of the EmployeesApp.Models.Employee. So, when calling this method, it will show this error.
To solve this issue, try to modify the SortEmployees method as below: using the Models.Employee
private List<Models.Employee> SortEmployees(List<Models.Employee> employees, String sortField, string currentSortField, SortDirection sortDirection)
{
It is due to the model class name and controller class name being the same due to which the correct modal is not being selected. In such a case you can explicitly add Models.Employee wherever you are using it or rename the controller name or model name itself.

NotMapped prop Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

good day ..
i created a model that has an property with [Notmapped] DataAnnotations and i created another class inherit from this model with same property but i add required DataAnnotations the problem is when i delete i got error "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
"
My Model :
[Key]
[Display(AutoGenerateField = true, AutoGenerateFilter = true, Description = "IDDescription", GroupName = "IDGroupName", Name = "IDName", ShortName = "IDShortName", Prompt = "IDPrompt", Order = 50, ResourceType = typeof(Resources.BaseEntity))]
public long ID { get; set; }
[StringLength(207, ErrorMessageResourceName = "StringTooMuch", ErrorMessageResourceType = typeof(Resources.BaseSlider))]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "DetailsRequired", ErrorMessageResourceType = typeof(Resources.BaseSlider))]
[Display(Name = "Description", ResourceType = typeof(Resources.BaseSlider))]
public string Description { get; set; }
[NotMapped]
public string ShortDescription
{
get
{
if (Description.Length <= 207)
{
return Description;
}
return Description.Substring(0, 207);
}
}
[Display(Name = "HasBTN", ResourceType = typeof(Resources.BaseSlider))]
public bool HasBTN { get; set; }
[Display(Name = "Is Image Dark")]
public bool IsDark { get; set; }
[Display(Name = "Link", ResourceType = typeof(Resources.BaseSlider))]
public string Link { get; set; }
[Display(Name ="Slider Type")]
public long SliderTypeID { get; set; }
[NotMapped]
//[ImageValidation(".jpg,.png,.japg", OriginalWidth = 1920, OriginalHeight = 600)]
[Display(AutoGenerateField = true, AutoGenerateFilter = true, Description = "ImagePathDescription", Name = "ImagePathName", ResourceType = typeof(Resources.BaseMore))]
public virtual HttpPostedFileBase ImagePathFile { get; set; }
#endregion
#region Relations
public virtual IList<BaseSliderPhotoUpload> Photos { get; set; }
public virtual BaseLookup SliderType { get; set; }
#endregion
public BaseSlider()
{
Photos = new List<BaseSliderPhotoUpload>();
}
and the class i created :
public class BaseSliderCreate : BaseSlider
{
#region Data
[NotMapped]
[Required]
//[ImageValidation(".jpg,.png,.japg", OriginalWidth = 1920, OriginalHeight = 600)]
[Display(AutoGenerateField = true, AutoGenerateFilter = true, Description = "ImagePathDescription", Name = "ImagePathName", ResourceType = typeof(Resources.BaseMore))]
public override HttpPostedFileBase ImagePathFile { get; set; }
#endregion
}
in delete actionresult code :
public ActionResult DeleteConfirmed(Guid id)
{
BaseSlider SliderObject = db.Sliders.Where(x => x.GUID == id && x.Deleted == null).FirstOrDefault();
SliderObject.Deleted = DateTime.Now;
SliderObject.DeletedByID = _CurrentUser.ID;
// Delete All Photos
DeletePhoto DeletePhoto = new DeletePhoto();
var DeletedPhotoName = new List<string>();
foreach (var name in SliderObject.Photos)
{
DeletedPhotoName.Add(name.FileName);
}
if (DeletePhoto.PhotoDeleted("Slider", DeletedPhotoName))
{
try
{
db.SliderPhotos.RemoveRange(SliderObject.Photos);
db.Entry(SliderObject).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
ErrorList.Add(ex.Message);
throw;
}
}
else
{
ErrorList.Add(DeletePhoto.ErrorMessage);
}
ViewBag.ErrorList = ErrorList;
return RedirectToAction("Delete", new { id = SliderObject.GUID });
}
when i save change i got error
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
i checked i found the EntityValidationErrors is that ImagePathFile is required..
thanks for helping my and i apologist for my bad English

Store update, insert, or delete statement affected an unexpected number of rows (0)

I try to update my Products table but i can't because throw an error.
This is my hardcode controller:
[HttpPost]
public ActionResult EditProduct(ProductsViewModel productViewModel)
{
TechStoreEntities context = new TechStoreEntities();
Product newProduct = new Product
{
ProductId = productViewModel.ProductId,
Name = productViewModel.Name,
Price = productViewModel.Price,
Discount = productViewModel.Discount,
Quantity = productViewModel.Quantity,
Size = productViewModel.Size,
Description = productViewModel.Description,
ProducerName = productViewModel.ProducerName,
PaymentMethods = productViewModel.PaymentMethods,
CategoryID = productViewModel.CategoryID,
SubcategoryID = productViewModel.SubcategoryID,
IsNew = productViewModel.IsNew,
IsEnable = productViewModel.IsEnable
};
context.Entry(newProduct).State = EntityState.Modified;
context.SaveChanges();
ViewBag.CategoryID = new SelectList(context.Categories.Where(c => c.SubCategoryID == null), "CategoryID", "Name");
ViewBag.SubcategoryID = new SelectList(context.Categories.Where(c => c.SubCategoryID != null), "CategoryID", "Name");
return RedirectToAction("Products");
}
This is a model:
public class ProductsViewModel
{
public int ProductId { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public int Discount { get; set; }
public int Quantity { get; set; }
public string Size { get; set; }
public string Description { get; set; }
public string ProducerName { get; set; }
public string PaymentMethods { get; set; }
public bool IsNew { get; set; }
public bool IsEnable { get; set; }
public string Category { get; set; }
public int CategoryID { get; set; }
public string Subcategory { get; set; }
public int SubcategoryID { get; set; }
public DateTime? CreateDate { get; set; }
}
I use strongly typed view:
#model MyTechStore.Models.ProductsViewModel
I add in a view:
#Html.HiddenFor(model => model.ProductId)
When i start app and enter some data to update existing data and press save, throw me exception:
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException
When i debugging i saw that only the ProductId was 0. Everything else is OK. I tested with scaffolding controller but there is OK. I want to use view model, not as scaffolding controller use the model from my database.
Can someone tell me where i'm wrong?
My GET method:
public ActionResult EditProduct(int? id)
{
TechStoreEntities context = new TechStoreEntities();
ProductsManipulate product = new ProductsManipulate();
ProductsViewModel editProduct = product.EditProduct(id);
ViewBag.CategoryID = new SelectList(context.Categories.Where(c => c.SubCategoryID == null), "CategoryID", "Name");
ViewBag.SubcategoryID = new SelectList(context.Categories.Where(c => c.SubCategoryID != null), "CategoryID", "Name");
return View(editProduct);
}
And my data access layer:
public ProductsViewModel EditProduct(int? id)
{
TechStoreEntities context = new TechStoreEntities();
Product dbProduct = context.Products.Find(id);
ProductsViewModel product new ProductsViewModel
{
Name = dbProduct.Name,
Price = dbProduct.Price,
Quantity = dbProduct.Quantity,
CategoryID = dbProduct.CategoryID,
SubcategoryID = dbProduct.SubcategoryID,
IsNew = dbProduct.IsNew
};
return product;
}
You need to populate ProductId in ProductsViewModel
public ProductsViewModel EditProduct(int? id)
{
TechStoreEntities context = new TechStoreEntities();
Product dbProduct = context.Products.Find(id);
ProductsViewModel product = new ProductsViewModel()
{
// You need this line to pass the value to View
ProductId = dbProduct.ProductId,
Name = dbProduct.Name,
Price = dbProduct.Price,
Quantity = dbProduct.Quantity,
CategoryID = dbProduct.CategoryID,
SubcategoryID = dbProduct.SubcategoryID,
IsNew = dbProduct.IsNew
};
return product;
}
What that error is saying, is that EF tried to update a Product with those fields, but the it returned 0 RowCount therefore it knows something went wrong.
As you have mentioned before, the ProductId is 0, meaning you probably don't have a Product with that ID, and therefore when EF tries to update it, the row count is 0, which causes EF to throw a DbUpdateConcurrencyException.
You need to make sure your Id is populated if you want to an update an existing product.
Otherwise if you want an upsert (Update or Insert) you first need to check if a record exists for your given ProductId and if it does, do update, otherwise do insert.

code first Entity Framework not saving to database

Ok, I am doing a project with entity framework 6. I have my class laid out. When I try to add the information to the database; it gives me following errors:
The best overloaded method match for 'System.Data.Entity.DbSet<img_site_codefi.DAL.DefaultConnection>.Add(img_site_codefi.DAL.DefaultConnection)' has some invalid arguments
Argument 1: cannot convert from 'AnonymousType#1' to 'img_site_codefi.DAL.DefaultConnection'
Here is my controller:
public ActionResult Contact(customer cust)
{
try
{
if (ModelState.IsValid)
{
cust.Tele_comp();
saveIntoDb(cust); // database
SendMail(cust); // mail sender
return RedirectToAction("Submited", "Home");
}
return null;
}
catch (DataException)
{
return View(cust);
}
}
private void saveIntoDb(customer cust)
{
using (var cust_In = new DefaultConnection())
{
var customer = new {fname = cust.fname,lname = cust.lname, tele = cust.tele, email = cust.email, reasn = cust.reasn };
//cust_In.customers.Add(customer); //HERE IS THE ERROR!!!
cust_In.SaveChanges();
}
}
and here is the model:
[Key]
[] // how to assign a number automatically
public int Cust_Id { get; set; }
[Required(ErrorMessage = "first name is required!")]
[Display(Name = "First name")]
public string fname { get; set; }
[Display(Name = "Last name")]
public string lname { get; set; }
[Required(ErrorMessage = "area code is required!")]
[StringLength(3)]
[RegularExpression(#"^[0-9]{3,}$", ErrorMessage = "Minimum 3 numbers required & contain only numbers")]
[Display(Name = "Telephone")]
public string tel_area { get; set; }
[Required(ErrorMessage = "first three numbers are required!")]
[StringLength(3)]
[RegularExpression(#"^[0-9]{3,}$", ErrorMessage = "Minimum 3 numbers required & contain only numbers")]
public string fir_thr_tel { get; set; }
[Required(ErrorMessage = "last four numbers are required!")]
[StringLength(4)]
[RegularExpression(#"^[0-9]{4,}$", ErrorMessage = "Minimum 4 numbers required & contain only numbers")]
public string lst_fur_tel { get; set; }
[Required(ErrorMessage = "E-mail is required!")]
[RegularExpression("^[a-zA-Z0-9_\\.-]+#([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]
[Display(Name = "Email")]
public string email { get; set; }
[Required(ErrorMessage = "A reason is required!")]
[Display(Name = "Reason")]
public string reasn { get; set; }
public string tele { get; set; }
Also, how do I generate a number automatically for the "Cust_Id" like a database do with the sql code IDENTITY or computed.
You have 2 problems. First, this line is wrong:
var customer = new {fname = cust.fname,lname = cust.lname, tele = cust.tele, email = cust.email, reasn = cust.reasn };
You are creating an anonymous type instead of a customer object. Try this instead:
var customer = new customer
{
fname = cust.fname,
lname = cust.lname,
tele = cust.tele,
email = cust.email,
reasn = cust.reasn
};
Secondly your context DefaultConnection is wrong and contains this:
public DbSet<DefaultConnection> customers { get; set; }
You are creating a DbSet of your context class instead of customers. This should be:
public DbSet<customer> customers { get; set; }
You cannot add Anonymous typed class or Dynamic to a DbSet so you need to create an instance class of customer in order to be added to your DbSet.
public ActionResult Contact(Customer cust)
{
try
{
if (ModelState.IsValid)
{
cust.Tele_comp();
saveIntoDb(cust); // database
SendMail(cust); // mail sender
return RedirectToAction("Submited", "Home");
}
return null;
}
catch (DataException)
{
return View(cust);
}
}
private void saveIntoDb(Customer cust)
{
using (var cust_In = new DbContext())
{
var customer = new Customer {fname = cust.fname,lname = cust.lname, tele = cust.tele, email = cust.email, reasn = cust.reasn };
cust_In.Customers.Add(customer); //HERE IS THE ERROR!!!
cust_In.SaveChanges();
}
}
Also your DbContext.cs class should have this instead of your code:
public DbSet<Customer> Customers { get; set; }
For the generation of primary key you should use this:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Make sure you try this tutorial first:
http://msdn.microsoft.com/en-us/data/jj572366.aspx

Categories

Resources