i am having problem on inserting multiple data in two tables.
Here is my code
Context Class
var userId = Convert.ToUInt32(user.Single(logon => logon.Type == CustomClaimTypes.UserId).Value);
/*Create access table for insert*/
var modules = p.Select(collection => new Accountcollection
{
AccountId = userId,
Amount = collection.Amount,
CashSource = collection.CashSource,
CollectionDate = collection.CollectionDate,
CreatedDatetime = DateTime.Now,
UpdatedDatetime = DateTime.Now,
}).ToList();
_context.Accountcollection.AddRange(modules);
var calendar_event = p.Select(collection => new Accountcalendarevents
{
AccountId = userId,
Subject = collection.CashSource,
Description = collection.CashSource,
Start = collection.CollectionDate,
End = collection.CollectionDate,
ThemeColor = "blue",
Isfullday = true,
Status = "1",
CreatedBy = userId,
CreatedDatetime = DateTime.Now,
UpdatedBy = userId,
UpdatedDatetime = DateTime.Now
}).ToList();
_context.Accountcalendarevents.AddRange(calendar_event);
_context.SaveChanges();
}
This is my collection model
public partial class Accountcollection
{
[Key]
public long Id { get; set; }
public long AccountId { get; set; }
public double? Amount { get; set; }
public string CashSource { get; set; }
public DateTime CollectionDate { get; set; }
public DateTime? CreatedDatetime { get; set; }
public DateTime? UpdatedDatetime { get; set; }
//public Accountcalendarevents Accountcalendarevents { get; set; }
public virtual Accountmaster Account { get; set; }
}
And this is my Caldendar Manager Events Model
public class Accountcalendarevents
{
[Key]
public long Id { get; set; }
public long AccountId { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public string ThemeColor { get; set; }
public bool Isfullday { get; set; }
public string Status { get; set; }
public long CreatedBy { get; set; }
public DateTime CreatedDatetime { get; set; }
public long UpdatedBy { get; set; }
public DateTime UpdatedDatetime { get; set; }
}
The problem is when I insert only 1 data in works fine but if I try to insert 2 or more, i am getting this kind of exception
Exception i got
But, when I commented
var calendar_event = p.Select(collection => new Accountcalendarevents
{
//AccountId = userId, <-- when I comment this line
Subject = collection.CashSource,
Description = collection.CashSource,
Start = collection.CollectionDate,
End = collection.CollectionDate,
ThemeColor = "blue",
Isfullday = true,
Status = "1",
CreatedBy = userId,
CreatedDatetime = DateTime.Now,
UpdatedBy = userId,
UpdatedDatetime = DateTime.Now
}).ToList();
it works properly on multiple data insertion.
Hope you helped me with this. Thank you!
Related
I apologize for the question, but I'm still not good at ASP.NET MVC 5, I ask for help, the task is as follows:
There is a database with two related tables, RequestProcessing and RequestType. The value of the DeadLine column of the RequestProcessing table should change depending on the TimeComplete value of the RequestType table, namely, it consists of the values
RequestProcessing.DeadLine = RequestProcessing.Date + RequestType.TimeComplete
I apologize for such rude formulations. Below I give the classes themselves and the controller method in which I want to get this
public class RequestProcessing
{
public int Id { get; set; }
[Display(Name = "Дата поступления")]
[Required]
public DateTime Date { get; set; }
[Display(Name = "Комментарий")]
public string Comment { get; set; }
[Display(Name = "Выполнить до")]
[Required]
public DateTime DeadLine { get; set; }
[Display(Name = "ИД заявки")]
[Required]
public int RequestId { get; set; }
public Request Request { get; set; }
[Display(Name = "ФИО")]
public int? SpecialistId { get; set; }
public Specialist Specialist { get; set; }
[Display(Name = "Статус заявки")]
public int? StatusId { get; set; }
public Status Status { get; set; }
[Display(Name = "Тип заявки")]
public int? TypeId { get; set; }
[ForeignKey ("TypeId")]
public RequestType RequestType { get; set; }
}
public class RequestType
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "Тип заявки")]
[Required]
[StringLength(50, ErrorMessage = "Данное поле должно содержать не более 50 символов")]
public string TypeName { get; set; }
[Display(Name = "Время на выполнение")]
[Required]
public double TimeComplete { get; set; }
[Display(Name = "Описание")]
[StringLength(300, ErrorMessage = "Данное поле должно содержать не более 300 символов")]
public string Description { get; set; }
[ForeignKey("TypeId")]
public virtual ICollection<RequestProcessing> RequestProcessings { get; set; }
public RequestType()
{
RequestProcessings = new List<RequestProcessing>();
}
}
public class RequestProcessingController : Controller
{
[HttpPost]
public ActionResult EditRequestProcessing(RequestProcessing rProcessing)
{
if (ModelState.IsValid)
{
RequestProcessing newRProcessing = dbRP.RequestProcessings.Find(rProcessing.Id);
newRProcessing.Comment = rProcessing.Comment;
newRProcessing.SpecialistId = rProcessing.SpecialistId;
newRProcessing.StatusId = rProcessing.StatusId;
newRProcessing.TypeId = rProcessing.TypeId;
newRProcessing.DeadLine = rProcessing.Date.AddMinutes(rProcessing.RequestType.TimeComplete);
dbRP.Entry(newRProcessing).State = EntityState.Modified;
dbRP.SaveChanges();
return RedirectToAction("RequestProcessing");
}
return View();
}
}
Just use the include, and fill, and then iterate in your view
Your Action
public ActionResult EditRequestProcessing(RequestProcessing rProcessing)
{
if (ModelState.IsValid)
{
// ... do your stuff blah blah
// get related data
var relatedProcessingData = db.RequestProcessing.Include(p=>p.RequestType);
//...
}
...
}
In your view
#Html.DisplayFor(modelItem => item.relatedProcessingData.RequestType)
Edit/Update: I saw you wanted the dead line, just compute calculate that in your action with a new ViewModel Object.
I would recommend a create new ViewModel like so RequestProcessingDeadLineViewModel
public class RequestProcessingDeadLineViewModel
{
public int Id { get; set; }
// Fill this in your business layer
public List<DateTime> DeadLine { get ; set; }
}
Or in the action
public ActionResult EditRequestProcessing(RequestProcessing rProcessing)
{
if (ModelState.IsValid)
{
// ... do your stuff blah blah
// get related data
var relatedProcessingData = db.RequestProcessing.Include(p=>p.RequestType);
// new deadline VM
var deadLineVM = new RequestProcessingDeadLineViewModel();
// copy your data to your ViewModel
foreach(...)
deadLineVM.DeadLine = deadLineVM.Date + + deadLineVM.TimeComplete;
//...
}
...
}
In model I have 3 tables in relation to many many.
public class Order
{
[Key]
public int IdOrder { get; set; }
public string UserId { get; set; }
public virtual User User { get; set; }
public int IdOrderAttachment { get; set; }
public virtual OrderAttachment OrderAttachment { get; set; }
public virtual ICollection<Employee> Employee { get; set; }
[Required(ErrorMessage = "Specify the date of order acceptance")]
[Display(Name = "Date of acceptance of the order")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTimeDateOfAcceptance { get; set; }
[Display(Name = "Date of completion planning")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? DateOfCompletionPlanning { get; set; }
[Display(Name = "End Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? EndDate { get; set; }
[Required(ErrorMessage = "Enter the subject")]
[MaxLength(200, ErrorMessage = "Name max 200 characters")]
[Display(Name = "Subject")]
public string Subject { get; set; }
public virtual ICollection<OrderPosition> OrderPosition{ get; set; }
}
public class OrderPosition
{
[Key]
public int IdOrderPosition { get; set; }
public int IdOrder { get; set; }
public int IdPosition { get; set; }
public virtual Order Order { get; set; }
public virtual Position Position { get; set; }
}
public class Position
{
[Key]
public int IdPosition { get; set; }
[Column(TypeName = "nvarchar(MAX)")]
[Display(Name = "Description")]
[UIHint("tinymce_jquery_full"), AllowHtml]
public string Description { get; set; }
public virtual ICollection<OrderPosition> OrderPosition { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrder(HttpPostedFileBase file, DataOrderUserViewModel viewModel)
{
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
if (file != null && file.ContentLength > 0)
{
string path = "/Content/Layout/CompanyFile";
if (!Directory.Exists(HttpContext.Server.MapPath(path)))
{
Directory.CreateDirectory(HttpContext.Server.MapPath(path));
}
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Path.Combine(HttpContext.Server.MapPath(path), filename));
viewModel.NameFile = path+ "/" + filename;
//var nameFile = Path.GetFileName(file.FileName);
//var path = Path.Combine(Server.MapPath("/Content/Layout/CompanyFile"), nameFile);
//file.SaveAs(path);
}
var order = new Order()
{
DateTimeDateOfAcceptance = viewModel.DateTimeDateOfAcceptance,
Subject= viewModel.Subject,
UserId = userId
};
var position = new Position ()
{
Description = viewModel.Description
};
var orderAttachment = new OrderAttachment ()
{
NameFile= viewModel.NameFile,
Description = viewModel.Description2
};
db.Order.Add(order);
db.Position.Add(position);
db.OrderAttachment.Add(orderAttachment);
db.SaveChanges();
}
return RedirectToAction("Index", "Administration");
}
My question is how to write data to the OrderPosition table.
I understand that I should first write data in the Order and Position table.
Then, having two keys from these arrays, I should read them and send them to the OrderPosition as external keys where they will be saved.
What should a record of these instructions look like?
Do I need to define the following relationships in my case?
modelBuilder.Entity<OrderPosition>()
.HasKey(c => new { c.IdOrder , c.IdPosition });
modelBuilder.Entity<Order>()
.HasMany(c => c.Subject )
.WithRequired()
.HasForeignKey(c => c.IdOrder );
modelBuilder.Entity<Position>()
.HasMany(c => c.Description )
.WithRequired()
.HasForeignKey(c => c.IdPosition );
I am using code-first Entity Framework in my ASP.NET MVC project
I have these tables
User
public class User:IBaseEntity
{
public User()
{
UserRoles = new List<UserRole>();
}
public int ID { get; set; }
public int RoleId { get; set; }
public string Email { set; get; }
public string Password { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public string Company { set; get; }
public string Address1 { set; get; }
public string Address2 { set; get; }
public string City { set; get; }
public string PostalCode { set; get; }
public string Country { set; get; }
public string State { set; get; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
Role
public class Role : IBaseEntity
{
public int ID { get; set; }
public string RoleName { get; set; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
}
UserRole
public class UserRole : IBaseEntity
{
public int ID { get; set; }
public int UserId { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
IBaseEntity
public interface IBaseEntity
{
int ID { get; set; }
}
I need seed data User with UserRole
How can I put UserRole in method create User?
public void CreateRoles(CMSDbContext context)
{
if (context.Roles.Count() == 0)
{
List< Role> listRole = new List<Role>()
{
new Role()
{
RoleName = "Admin",
Active = true,
CreatedOn = DateTime.Now
},
new Role()
{
RoleName = "User",
Active = true,
CreatedOn = DateTime.Now
}
};
context.Roles.AddRange(listRole);
context.SaveChanges();
}
}
public void CreateUser(CMSDbContext context)
{
if (context.Users.Count() == 0)
{
List<User> listUser = new List<User>()
{
new User()
{
FirstName = "David",
LastName = "Lima",
Active = true,
Email = "admin#domain.com",
Address1 = "New York",
Address2 = "Chicago",
Company = "Test",
CreatedOn = DateTime.Now,
PostalCode = "123456",
State = "Test",
City = "test",
UserRoles =???
Password = CMS.Common.HashMD5.CreateMD5("12356")
}
};
context.Users.AddRange(listUser);
context.SaveChanges();
}
}
}
Please focus on method CreateUser have property UserRole, not sure what I can put here. I also create some roles in Role table (admin, user)
I am getting stuck at this point.
Any help will be appreciated
Thanks all
I have a Contractor class and a Musicians Class which inherits the Contractor class. I am running migration and it will only build one Contractor table with Musicians fields included. I want a Contractor table and Musicians table that follows my domain models. It creates Instrument table correctly. Does this have something to do with the fact I am using inheritance on the classes?
public class Contractor
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
public DateTime SuspendDate { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public string ImageName { get; set; }
public bool Suspended { get; set; }
}
public class Musician : Contractor
{
public Guid MusiciansId { get; set; }
public string WebsiteLink { get; set; }
public string YouTubeLink { get; set; }
public string SoundCloudLink { get; set; }
public string ReverbNationLink { get; set; }
public int YearsOfExperience { get; set; }
[DataType(DataType.Date)]
public DateTime NextDateAvailable { get; set; }
public Instrument Instrument { get; set; }
public int InstrumentId { get; set; }
public Contractor Contractor { get; set; }
public Guid ContractorId { get; set; }
}
My Migration script :
CreateTable(
"dbo.Contractor",
c => new
{
ID = c.Guid(nullable: false),
FirstName = c.String(),
LastName = c.String(),
Email = c.String(),
ZipCode = c.String(),
Phone = c.String(),
Description = c.String(),
CreateDate = c.DateTime(nullable: false),
SuspendDate = c.DateTime(nullable: false),
ImageData = c.Binary(),
ImageMimeType = c.String(),
ImageName = c.String(),
Suspended = c.Boolean(nullable: false),
UnionMember = c.Boolean(),
MusiciansId = c.Guid(),
WebsiteLink = c.String(),
YouTubeLink = c.String(),
SoundCloudLink = c.String(),
ReverbNationLink = c.String(),
YearsOfExperience = c.Int(),
NextDateAvailable = c.DateTime(),
InstrumentId = c.Int(),
ContractorId = c.Guid(),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Contractor", t => t.ContractorId)
.ForeignKey("dbo.Instrument", t => t.InstrumentId, cascadeDelete: true)
.Index(t => t.InstrumentId)
.Index(t => t.ContractorId);
It is not a good idea to use inheritance in model classes.
You can add Type value for your Contractor and create another table for each type of contractor (Musician for example):
public enum ContractorType
{
Musician = 0
}
public class Contractor
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
public DateTime SuspendDate { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public string ImageName { get; set; }
public bool Suspended { get; set; }
public ContractorType contractorType { get; set; }
public Musician Musician { get; set; }
}
After doing some research the answer is: [Table] attribute above Musicians class.
http://www.codeproject.com/Articles/796521/Inheritance-in-Entity-Framework-Table-Per-Type
Error:
No mapping exists from object type eTrail.Models.Global.Address to a known managed provider native type.
The code that is throwing the error:
if (!WebSecurity.UserExists("me"))
{
WebSecurity.CreateUserAndAccount(
"me",
"password", new
{
FirstName = "Firstname",
LastName = "Lastname",
Email = "me#me.com",
Address = new Address
{
Street = "123 Stree",
Street2 = "",
City = "CityVille",
State = "UT",
Zip = "99999",
Country = "USA",
PhoneCell = "111.111.1111"
},
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now,
ImageName = ""
});
}
My User.cs Model:
public class User : IAuditInfo
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public Address UserAddress { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public ICollection<Role> Roles { get; set; }
public string ImageName { get; set; }
public User()
{
UserAddress = new Address();
Roles = new List<Role>();
}
}
The Address Model:
public class Address
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Street { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public string PhoneHome { get; set; }
public string PhoneCell { get; set; }
public string PhoneOther { get; set; }
public string FaxNumber { get; set; }
}
Any idea why I am getting this error? Both Model classes are in my DbContext class as DbSet and DbSet.
You used the wrong property name when you created the new user account. You used Address instead of UserAddress. Make the following change under the comment I added to the code.
if (!WebSecurity.UserExists("me"))
{
WebSecurity.CreateUserAndAccount(
"me",
"password", new
{
FirstName = "Firstname",
LastName = "Lastname",
Email = "me#me.com",
//Changed Address to UserAddress
UserAddress = new Address
{
Street = "123 Stree",
Street2 = "",
City = "CityVille",
State = "UT",
Zip = "99999",
Country = "USA",
PhoneCell = "111.111.1111"
},
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now,
ImageName = ""
});
}