ASP.NET MVC 3, SQL Server - sql-server

First I'll show you what I do, and that there is. My project in ASP.NET MVC 3.
This is model for table Business.
[Table("Business")]
public class Business
{
[Key]
public long? BusinessId { get; set; }
public Int32 LegalTypeId { get; set; }
public Int16 BusinessTypeId { get; set; }
public Int64 OwnerId { get; set; }
public Int32 MainIndustryFieldId { get; set; }
public String NameNative { get; set; }
public String NameEnglish { get; set; }
public Byte[] Logo { get; set; }
public DateTime CreateDate { get; set; }
public virtual User Owner { get; set; }//It is Forign key with user table
}
[Table("User")]
public class User
{
[Key]
public Int64 UserId { get; set; }
public String UserName { get; set; }
public String LoweredUserName { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String LoweredEmail { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public String PasswordQuestion { get; set; }
public String PasswordAnswer { get; set; }
public Boolean IsApproved { get; set; }
public Boolean IsLocked { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime CreateDate { get; set; }
public virtual Business Bussines { get; set; }
}
when I want to add information:
user.Business = new Business
{
OwnerId = user.UserId,
LegalTypeId = business.LegalTypeId,
BusinessTypeId = business.BusinessTypeId,
MainIndustryFieldId = business.MainIndustryFieldId,
NameNative = business.NameNative,
NameEnglish = business.NameEnglish,
Logo = business.Logo,
CreateDate = DateTime.Now
};
ctx.SaveChanges();
I get the following error:
Cannot insert explicit value for identity column in table 'Business'
when IDENTITY_INSERT is set to OFF.
In database column identity specification business chose is Identity Yes.
Somebody can tell what to do.

Can you make sure that in your EDMX model, your BusinessId is set to be handled by the database (property StoreGeneratedPattern = Identity)?? Also: why is your primary key nullable (long?) - makes no sense whatsoever. Your primary key must never be null !

BusinessId can not be empty/null since you have not specified that it should be autogenerated by Sql Server (which Identity means).
Since you are using Code First to generate your database, just change to:
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long? BusinessId { get; set; }

override OnModelCreating in DbContext and add in it following Fluent API:
modelBuilder.Entity<Business>().HasRequired(m => m.Address).WithRequiredPrincipal(m => m.Business).WillCascadeOnDelete(true);

Related

Resolve an issue for Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException

I have an issue during an insert operation into the table using Entity Framework Core.
_context.Entry(item).State = EntityState.Added;
var r = await _context.ServiceWorkOrders.AddAsync(item);
_context.SaveChangesAsync(); <-- (fails)
Some context when dealing with this issue.
The table is owned by client so I have to work around this issue
The table to insert into, contains triggers and stored procedures set to run after Insert/Update/Delete operations.
The table have relationship properties (Foreign keys)
The table's primary key is set to auto-increment, hence the primary key field of the inserting entity is set to 0, along with the fields that is required during this insert.
I am trying to use Stored Procedure directly using ExecuteSqlCommand, but I would prefer to use EF to manage the database access. Moreover, correct me if I am wrong, I would have to list all the optional parameters in the Stored Procedure in order to add the entity in to prevent writing into the wrong fields. Currently this method inserts the entity, but it writes on the wrong fields, even if I used SqlParameters("#named_field", value).
I have tried using the Synchronous method as well, but it gives the same exception.
The exception returned:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.'
edit:
Here is the entity model:
[Table("ASM_ServiceWorkOrder")]
public class ServiceWorkOrder: BaseEntity
{
[Key, Column(name: "ROWUID"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RowUID { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string CompanyID { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DocNumber { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string RevisionNumber { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string CustomerDirectoryID { get; set; }
[ForeignKey("CustomerLocation")]
public Int32? CustomerLocationRowUID { get; set; }
public AssetLocation CustomerLocation { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string WorkOrderType { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string IssueType { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string AssetItemCode { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string AssetSerialNo { get; set; }
[ForeignKey("AssetRegister")]
public int? AssetRegisterROWUID { get; set; }
public AssetRegister AssetRegister { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string ProjectDirectoryID { get; set; }
[Column(TypeName = "nvarchar(10)")]
public string Priority { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string Status { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string StatusForClient { get; set; }
public bool? Billable { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal? QuotedFee { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DueDate { get; set; }
[Column(TypeName = "nvarchar(240)")]
public string Description { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string ReportedBy { get; set; }
[Column(TypeName = "datetime")]
public DateTime? ReportedDate { get; set; }
[Column(TypeName = "nvarchar(35)")]
public string BusinessDataType { get; set; }
[Column(TypeName = "nvarchar(240)")]
public string DocRemarks { get; set; }
[Column(TypeName = "nvarchar(2000)")]
public string ErrorText { get; set; }
public Guid? RowGlobalUID { get; set; }
public Int32? HeaderROWUID { get; set; }
[Column(TypeName = "datetime"), DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? DateOfDocument { get; set; }
//[Timestamp]
//public byte RowVersion { get; set; }
//public IList<ServiceWorkOrderAttachment> Attachments { get; set; }
public IList<ServiceWorkOrderDetails> Details { get; set; }
}
Are u sure u created ITEM? And indicate table where u try save row?
If u wanna insert row in table u must create your item first.
f.ex:
var = new ServiceWorkOrders(){Column1=var1,Column2=var2 etc.};
await _context.ServiceWorkOrders.AddAsync<ServiceWorkOrders>(item);
await _context.SaveChangesAsync();

SQL Server the column name is specified more than once in the set clause. Entity framework issue

When I do an insert using EF6, I get this error
The column name 'employee_id' is specified more than once in the SET clause. A column cannot be assigned more than one value in the same SET clause. Modify the SET clause to make sure that a column is updated only once. If the SET clause updates columns of a view, then the column name 'employee_id' may appear twice in the view definition
My models looked like this:
public class Entity
{
public Entity()
{
IsActive = true;
IsDeleted = false;
DateCreated = DateTime.Now;
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID { get; set; }
public int CompanyID { get; set; }
public int SubID { get; set; }
public DateTime DateCreated { get; set; }
public bool IsTransient()
{
return EqualityComparer<long>.Default.Equals(ID, default(long));
}
public bool IsDeleted { get; set; }
public bool IsActive { get; set; }
}
public partial class NextOfKin : Entity
{
[Required]
public long employee_id { get; set; }
[StringLength(100)]
[Required]
public string nok_first_name { get; set; }
[StringLength(100)]
[Required]
public string nok_last_name { get; set; }
[StringLength(300)]
[Required]
public string nok_address { get; set; }
[StringLength(100)]
public string nok_email { get; set; }
[StringLength(100)]
public string nok_phone { get; set; }
[StringLength(100)]
public string nok_employer { get; set; }
[StringLength(300)]
public string nok_work_address { get; set; }
[StringLength(100)]
[Required]
public string nok_relationship { get; set; }
public virtual Employee Employee { get; set; }
}
public class Employee : Entity
{
//Person Records
public long UserId { get; set; }
public int TitleId { get; set; }
public int? ReligionId { get; set; }
public string SerialNo { get; set; }
[StringLength(100)]
[Required]
public string FirstName { get; set; }
[StringLength(100)]
[Required]
public string LastName { get; set; }
}
My insert code into next of kin was like this.
NextOfKin nextOfKin = new NextOfKin();
nextOfKin.employee_id = newEmployee.ID;
nextOfKin.nok_first_name = "Friday";
nextOfKin.nok_last_name = "Ben";
nextOfKin.nok_address = "XXX";
nextOfKin.nok_email = "xa#xo.com";
nextOfKin.nok_phone = "023938494";
nextOfKin.nok_employer = "50 Queens Street";
nextOfKin.nok_work_address = "51 Queens Street";
nextOfKin.nok_relationship = "Neighbour";
db.NextOfKins.Add(nextOfKin);
db.SaveChanges();
I got an error like this using EF Core
'PropertyNameID' is specified more than once in the SET clause or
column list of an INSERT. A column cannot be assigned more than one
value in the same clause. Modify the clause to make sure that a column
is updated only once. If this statement updates or inserts columns
into a view, column aliasing can conceal the duplication in your code.
It turned out that I had the case wrong in my relatonship
In My business object I had the foreign key set with the wrong case.
public int PropertyNameID { get; set; }
[ForeignKey("PropertyNameId")] public virtual PropertyNameExt PropertyName { get; set; }
Should have been
[ForeignKey("PropertyNameID")] public virtual PropertyNameExt PropertyName { get; set; }
To fix this, remove the relationship on next of kin model, then do migration.
To remove, remove public virtual Employee Employee { get; set; } from NextOfKin model.
The reason for this issue is as follow:
Relationships are only created properly if you name the reference property properly. In this case you should use EmployeeID instead of employee_id for the relationship between next of kin and employee.
The Employee model does not have a link back to the next of kin model. If it's a one to many you can add the property below to the Employee model.
public virtual List NextOfKins{get; set;} //if you need lazy loading
or
public List NextOfKins{get; set;} //if you don't need lazy loading

The INSERT statement conflicted with the FOREIGN KEY. Entity includes ForeignKey Id property

I'm doing one to many relationship database with Entity Framework with an Id property.
I have two model classes:
public class PersonModel
{
[Key]
public int PersonId { get; set; }
public string NickName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int TeamRefId { get; set; }
[ForeignKey("TeamRefId")]
public virtual TeamModel TeamModel { get; set; }
}
public class TeamModel
{
public TeamModel()
{
TeamMembers = new List<PersonModel>();
this.Tournaments = new HashSet<TournamentModel>();
}
[Key]
public int TeamId { get; set; }
public string TeamName { get; set; }
public virtual ICollection<PersonModel> TeamMembers { get; set; }
public virtual ICollection<TournamentModel> Tournaments { get; set; }
public virtual MatchUpEntryModel MatchupEntry { get; set; }
public virtual MatchUpModel Matchup { get; set; }
}
When I'm trying to create a new Person entity, I get this error:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.PersonModel_dbo.TeamModel_TeamRefId". The conflict occurred in database "Tournament2", table "dbo.TeamModel", column 'TeamId'.
Making Foreign Key in Person Model nullable should solve your problem
note that created person will have No Team until you Modify it later after your create Team
public class PersonModel
{
[Key]
public int PersonId { get; set; }
public string NickName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int? TeamRefId { get; set; }
[ForeignKey("TeamRefId")]
public virtual TeamModel TeamModel { get; set; }
}

Invalid object name 'dbo.customers1'

I'm getting the error "Invalid object name 'dbo.customers1'" on my view...
#foreach (var item in Model)
{
<tr>
<td>#item.orderid</td>
<td>#item.customer.firstname</td>
I have the ViewModel classes...
public class orders
{
[Key]
public int orderid { get; set; }
public System.DateTime createdate { get; set; }
public string createdby { get; set; }
public Nullable<int> statusid { get; set; }
public Nullable<System.DateTime> pickup { get; set; }
public Nullable<System.DateTime> dropoff { get; set; }
public Nullable<System.DateTime> scheduledout { get; set; }
public Nullable<System.DateTime> scheduledin { get; set; }
public bool instorepickup { get; set; }
public string paymenttype { get; set; }
public System.DateTime reservationstart { get; set; }
public System.DateTime reservationend { get; set; }
public bool morningpickup { get; set; }
public Nullable<int> customerid { get; set; }
public string notes { get; set; }
public string shippingtype { get; set; }
public Nullable<decimal> shippingestimate { get; set; }
public virtual customer customer { get; set; }
public virtual ICollection<invoice> invoices { get; set; }
public virtual orderstatuses orderstatuses { get; set; }
public virtual ICollection<serialorders> serialorders { get; set; }
}
and
public class customers
{
[Key]
public int customerid { get; set; }
public System.DateTime createdate { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
[Required]
public string billingaddress1 { get; set; }
public string billingaddress2 { get; set; }
[Required]
public string billingcity { get; set; }
public string billingstate { get; set; }
[Required]
public string billingzip { get; set; }
[Required]
public string billingcountry { get; set; }
public string phone { get; set; }
[Required]
public string email { get; set; }
[Required]
public string shippingaddress1 { get; set; }
public string shippingaddress2 { get; set; }
[Required]
public string shippingcity { get; set; }
public string shippingstate { get; set; }
[Required]
public string shippingzip { get; set; }
[Required]
public string shippingcountry { get; set; }
public bool goodstanding { get; set; }
public string userid { get; set; }
public Nullable<DateTime> insuranceexp { get; set; }
public virtual ICollection<invoice> invoices { get; set; }
public virtual ICollection<order> orders { get; set; }
}
this is my model...
And I have a data access layer...
public DbSet<tvc.viewModels.orders> orders { get; set; }
public DbSet<tvc.viewModels.customers> customers { get; set; }
The error is pretty straight-forward. There's no dbo.customers1 table in your database. As to why, there's really not enough information here to say, but the most likely causes are:
You're using Database First or Code First with an existing database, and your entities are out of sync with the database.
You're using Code First, don't have migrations enabled, and you've made a change to either your entities or your database. Again, out of sync.
You've specified an explicit table name, either via the Table attribute or fluent config, that doesn't exist. Either way, change either the explicit table name to what it should be or rename your database table so it matches.
There was an oversight in my ViewModel. I was pointing customer, which is the name of the database table and the model class, rather than the viewmodel class which is customers (with an s).

Better way to create database for a pricing system

I need to create a price table system so I am going to create these three tables in my database.
PricingTable (ID, Name, ServiceID, Style)
PricingTablePackages (ID, PricingTable_ID, Title, Price, PricePerTime, Info, Flag, Link)
PricingTablePackagesFeatures (ID, PricingTablePackages_ID, Feature, Value, MoreInfo)
Here one PriceTable can hold more then one PricingTablePackages and one PricingTablePackage can hold more then one PricingTablePackagesFeature.
Is any way to design a better model? In a single database Table ?
I am going to create a MVC3 Model for those table so what is the best way to do this kind of DB Table in a MVC3 Model?
I would use public virtual variables for 'lazy-loading' values when you need them using Entity Framework:
(variable types may be off depending on exactly what you want for each variable)
public class PricingTablePackages
{
public int ID { get; set; }
public int PricingTableID { get; set; }
public virtual PricingTable PricingTable { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public decimal PricePerTime { get; set; }
public string Info { get; set; }
public bool Flag { get; set; }
public string Link { get; set; }
}
public class PricingTablePackagesFeatures
{
public int ID { get; set; }
public int PricingTableID { get; set; }
public virtual PricingTable PricingTable { get; set; }
public string Feature { get; set; }
public string Value { get; set; }
public string MoreInfo { get; set; }
}
public class PricingTable
{
public int ID { get; set; }
public string Name { get; set; }
public int ServiceID { get; set; }
public virtual Service Service { get; set; } // if there is a Service class
public string Style { get; set; }
}

Resources