I've been trying to get something done in .NET EF for some time now.
My model looks like this:
public class Route
{
[Key]
public int RouteId { get; set; }
[Display(Name = "Rope")]
public int ropeId { get; set; }
public virtual Rope rope { get; set; }
[Display(Name = "Routesetter")]
public int routeSetterId { get; set; }
public virtual RouteSetter routeSetter { get; set; }
[Display(Name = "Secundary routesetter")]
public int? secundaryRouteSetterId { get; set; }
public virtual RouteSetter secundaryRouteSetter { get; set; }
[Display(Name = "Grade")]
public int gradeId { get; set; }
public virtual ClimbingGrade grade { get; set; }
[Display (Name = "Routename")]
public string name { get; set; }
[Display(Name = "Color")]
public int colorId { get; set; }
public virtual GripColor color { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display (Name ="Date set")]
public DateTime dateSet { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display (Name ="Date removed")]
public DateTime? dateRemoved { get; set; }
[Display (Name ="Marked for removal")]
public bool markedForRemoval { get; set; }
}
The controller:
public ActionResult Index()
{
var routes = db.Routes.Include(r => r.color).Include(r => r.grade).Include(r => r.rope).Include(r => r.routeSetter).Include(r => r.secundaryRouteSetter);
ViewBag.Page = "Routes";
return View(routes.ToList());
}
Now the color property is always null. while all other properties are loaded.
I can't seem to figure this one out. Any help would be welcome
EDIT
The GripColor clas:
public class GripColor
{
[Key]
public int GripColorId { get; set; }
[Display(Name = "Primary color")]
public string primaryColor { get; set; }
[Display(Name = "Secundary color")]
public string secundaryColor { get; set; }
public string displayName { get { return primaryColor + ' ' + secundaryColor; } }
public virtual List<Route> Routes { get; set; }
}
I assume the gripColors are OK in the database;
ViewBag.ColorID = new SelectList(db.Colors, "GripColorId", "displayName");
The above is used to populate a dropdown (wich works) And the colorId is stored correctly in the database
There is no foreign key relating the two tables, then how are you expecting to make inner joins between them?You should setup the relationship between these two tables and define the foreign key.You can use data annotations for this purpose or i highly recommend using fluent api.Check out this documentation for more info:
http://docs.efproject.net/en/latest/modeling/index.html
Related
I have 4 classes, 3 of them have many-to-many relationship with the main one Person. How can I create a multiselect dropdown for Person to select from the list of books, classes, and conferences? the person class has List of books, list of classes and list of conferences since a person can have more that one of each of these classes. The same thing goes for books, classes, and conferences. Each of these classes has a list of person since a book can have multiple writers, a class can have multiple instructors, and a conference can have multiple attendants. I'm not sure how to accomplish that and link the tables to each other. Any help will be much appreciated. I'm using entity framework code first.
Here's my classes:
public class Workshop
{
public Workshop()
{
Customers = new HashSet<Customer>();
}
[Key]
public int WorkshopID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Session sessions { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
public enum Session
{
NewWorkshopPanels,
Workshops,
PanelSessions
}
public class Paper
{
public Paper()
{
Customers = new HashSet<Customer>();
}
[Key]
public int PaperID { get; set; }
[DisplayName("Short Title")]
public string ShortTitle { get; set; }
[DisplayName("Paper Title")]
public string Title { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
[DisplayName("Published Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? PublishedDate { get; set; }
[DisplayName("Date Created")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime? CreateDate { get; set; }
[DisplayName("Due Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? DueDate { get; set; }
[DisplayName("Image Title")]
public string imgTitle { get; set; }
[DisplayName("Image")]
public string imgPath { get; set; }
[NotMapped]
public HttpPostedFileBase ImageFile { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
public virtual ICollection<FileUsed> Files { get; set; }
}
public class Conference
{
public Conference()
{
Customers = new HashSet<Customer>();
}
[Key]
public int ConferenceID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[DisplayName("Start Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime? EndDate { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh\\:mm}")]
public TimeSpan? StartTime { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh\\:mm}")]
public TimeSpan? EndTime { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
public virtual ICollection<FileUsed> Files { get; set; }
}
public class Customer
{
public Customer()
{
paper = new HashSet<Paper>();
workshop = new HashSet<Workshop>();
conference = new HashSet<Conference>();
}
[Key]
public int CustomerID { get; set; }
[DisplayName("First Name")]
public string FirstMidName { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
[DisplayName("Short Title")]
public string ShortTitle { get; set; }
[DisplayName("Title")]
public string Title { get; set; }
[DisplayName("Biography")]
public string Bio { get; set; }
public string Company { get; set; }
public bool? IsHallFame { get; set; }
[DisplayName("Hall of Fame Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? HallOfFameDate { get; set; }
public bool? IsInstructor { get; set; }
public bool? IsTechnicalCommittee { get; set; }
public bool? IsAuthor { get; set; }
[DisplayName("Full Name")]
public string FullName
{
get { return FirstMidName+" " +LastName; }
}
//public int? conferenceID { get; set; }
//public int? PaperID { get; set; }
//public int? WorkshopID { get; set; }
public CustomerRole customerRole { get; set; }
//public virtual Conference conference { get; set; }
//public virtual Workshop workshop { get; set; }
//public virtual Paper paper { get; set; }
public virtual ICollection<Conference> conference { get; set; }
public virtual ICollection<Workshop> workshop { get; set; }
public virtual ICollection<Paper> paper { get; set; }
public virtual ICollection<FileUsed> Files { get; set; }
}
public enum CustomerRole
{
Speaker = 1,
Attendant = 2
}
I'm fairly new to .NET MVC 5, coming from a primarily PHP background. I have a 'Project' model with a List collection in it. When I use just a test controller to save data into the collection, it will save into the database just fine.
The problem arises when I'm trying to pull information out of that collection, as it always comes back as null.
My Project model:
public class Project
{
public int ID { get; set; }
[Display(Name = "Project")]
public string ProjectNumber { get; set; }
[Display(Name = "Client")]
public string Client { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Display(Name = "Start Date")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[Display(Name = "Required Date")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime RequiredDate { get; set; }
public string ProjectManagerId { get; set; }
[ForeignKey("ProjectManagerId")]
[Display(Name = "Project Manager")]
public ApplicationUser ProjectManager { get; set; }
[Display(Name = "Project Members")]
public int[] ProjectMembers { get; set; }
[Display(Name = "Tasks")]
public List<ProjectTask> TaskCollection { get; set; }
}
public class ProjectDb : DbContext
{
public ProjectDb() : base("DefaultConnection")
{
}
public DbSet<Project> Projects { get; set; }
}
My ProjectTask model:
public class ProjectTask
{
public int Id { get; set; }
public int ProjectId { get; set; }
[ForeignKey("ProjectId")]
public virtual Project Project { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string TaskNotes { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DueDate { get; set; }
public int Duration { get; set; }
public TaskStatus Status { get; set; }
public TaskAlertLevel AlertLevel { get; set; }
public List<ProjectTask> SubTasks { get; set; }
public string Progress { get; set; }
}
public class ProjectTaskDb : DbContext
{
public ProjectTaskDb() : base("DefaultConnection")
{
}
public DbSet<Project> ProjectTasks { get; set; }
}
My controller where I'm just trying to see something other than null exceptions:
public ActionResult DetailTasks(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Project project = db.Projects.Find(id);
if (project == null)
{
return HttpNotFound();
}
var tasks = project.TaskCollection;
ViewBag.tasks = tasks;
return View(project);
}
Hopefully it's something completely obvious and stupid that escapes me right now!
Apologies in regards to the comments, for some reason I thought you were having issues loading up the initial project object. So looking at your Project entities you have lazy loading turned off because you are not using the virtual keyword:
public List<ProjectTask> TaskCollection { get; set; }
vs
public virtual List<ProjectTask> TaskCollection { get; set; }
When you do this you must either Explicitly or Eagerly load your TaskCollection
Exlicitly load:
Project project = db.Projects.Find(id);
db.Entry(project).List(a => a.TaskCollection).Load();
Eagerly Load:
Project project = db.Projects.where(a => a.ID == id).Include(b => b.TaskCollection).FirstOrDefault();
p.s. you may have to play with my context a bit as I'm not at a place where I can load-up VS
Hi you can try with changing this line: var tasks = project.TaskCollection; to like this: var tasks = project.TaskCollection.ToList();, it may help you
Full example/Changed Code:
public ActionResult DetailTasks(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Project project = db.Projects.Find(id);
if (project == null)
{
return HttpNotFound();
}
var tasks = project.TaskCollection.ToList();
ViewBag.tasks = tasks;
return View(project);
}
I believe this time you wont get null for the project.TaskCollection , if the data available in the database.
Hope the above the information was useful , kindly let me know your thoughts or feedbacks
Thanks
Karthik
I'm trying to update a many-to-many relationship. I have two models, diary and tags. The model diary contains a list of tags and tags contains a list of diaries. But whenever I try to add another tag to an existing list or change an existing one I get thrown an exception:
The entity type List`1 is not part of the model for the current context.
Does my way of updating even work on collections? Or is there another approach I should be looking at?
Diary Model
public class Diary
{
[Key]
public int IdDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
public string NameDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
public bool Locked { get; set; }
public ICollection<Entry> Entries { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "This field is required")]
public string Summary { get; set; }
public string ImageUrl { get; set; }
public ICollection<Tag> Tags { get; set; }
}
Entry Model
public class Entry
{
[Key]
public int IdEntry { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
[DataType(DataType.MultilineText)]
public string EntryText { get; set; }
[ForeignKey("Diary_IdDiary")]
public Diary Diary { get; set; }
public int Diary_IdDiary { get; set; }
public string EntryName { get; set; }
}
Tag Model
public class Tag
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Diary> Diaries { get; set; }
}
Update Method
public void UpdateDiary(Diary updatedDiary)
{
var searchResult = SearchDiary(updatedDiary);
if (searchResult != null)
{
updatedDiary.IdDiary = searchResult.IdDiary;
_context.Entry(searchResult).CurrentValues.SetValues(updatedDiary);
_context.Entry(searchResult.Tags).CurrentValues.SetValues(updatedDiary.Tags);
_context.SaveChanges();
}
}
SearchDiary Method
public Diary SearchDiary(Diary searchDiary)
{
var queryResult =
_context.Diaries.Include(d => d.Entries).Include(d => d.Tags)
.Where(d => (d.NameDiary == searchDiary.NameDiary && d.CreationDate == searchDiary.CreationDate) || d.IdDiary == searchDiary.IdDiary);
return queryResult.FirstOrDefault();
}
Thank you for reading
Here is one way:
DiaryModel
public class Diary
{
[Key]
public int IdDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
public string NameDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
public bool Locked { get; set; }
public virtual ICollection<Entry> Entries { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "This field is required")]
public string Summary { get; set; }
public string ImageUrl { get; set; }
public ICollection<Tag> Tags { get; set; }
}
EntryModel
public class Entry
{
[Key]
public int IdEntry { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
[DataType(DataType.MultilineText)]
public string EntryText { get; set; }
[ForeignKey("Diary_IdDiary")]
public virtual Diary Diary { get; set; }
public int Diary_IdDiary { get; set; }
public string EntryName { get; set; }
}
For Search
public Diary SearchDiary(int DiaryId)
{
return _context.Diaries
.Include(p => p.Entries)
.Include(p => p.Tags)
.FirstOrDefault(p => p.IdDiary == DiaryId);
}
For Update
public void UpdateDiary(Diary Diary)
{
_context.Update(Diary);
_context.SaveChanges();
}
You should pass the modified Diary object to the update functions.
I'm new in Asp.Net and Entity Framework and i have a little issue.
I know u can help me , because its simple and i only know how to do it in PHP XD
I Have 2 models
public class Suppliers
{
public int ID { get; set; }
public int ID_Guard { get; set; }
public string Supplier{ get; set; }
public string Description { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm tt}", ApplyFormatInEditMode = true)]
public DateTime Enter { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm tt}", ApplyFormatInEditMode = true)]
public DateTime Exit { get; set; }
public virtual Guard Guard { get; set; }
}
public class Guard
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Suppliers> Suppliers{ get; set; }
}
controller
public class SuppliersController : Controller
{
private SuppliersContext db = new SuppliersContext();
public ActionResult Index()
{
return View(db.Suppliers.ToList());
}
}
And i wanna pass to the view the 2 table data and relate it
When i go to index show me all the suppliers data and show the Guard name( the person who registered the supplier enter and exit)
Well its solved
var results = from c in db.Suppliers
join cn in db.Guard on c.ID_Guard equals cn.ID
where (c.ID_Guard == cn.ID)
select new Models.MyViewModel{ Name= cn.Name, ID = c.ID, Supplier=c.Supplier, Description=c.Description, Enter=c.Enter, Exit=c.Exit};
follow the below code it works and seems same like yours also i added the link hope you find It helpful
public class Product
{
public Product() { Id = Guid.NewGuid(); }
public Guid Id { get; set; }
public string ProductName { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
}
public class ProductCategory
{
public int Id { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
/////view model///
public class ProductViewModel
{
public Guid Id { get; set; }
[Required(ErrorMessage = "required")]
public string ProductName { get; set; }
public int SelectedValue { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
[DisplayName("Product Category")]
public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}
follow the below tutorial
relationship model
for basic join use below query
var dealercontacts = from contact in table1
join table2 in table2 on contact.Id equals another.ID
select contact;
Short Story:
I load a model instance from db, apply changes to it but when I want to update the changes, Validation exceptions happens for foreign key items which set as [Required] in model definition. I've found a work around but I don't know what is the right way to fix this?
Details:
I have a model as below:
public class Project
{
public int Id { get; set; }
[Required]
[StringLength(100, MinimumLength = 5]
public string Name { get; set; }
[Required]
public virtual ApplicationUser Client { get; set; }
[Key]
[ForeignKey("Client")]
public string ClientID;
[Required]
public virtual ApplicationUser ProjectManager { get; set; }
[Key]
[ForeignKey("ProjectManager")]
public string ProjectManagerID;
[Range(0,100)]
[Required]
public int Progress { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CreateDate { get; set; }
[Column("Disabled")]
public bool Disabled{ get; set; }
[Column("Status")]
public string Status{ get; set; }
}
Whenever I fetch model information from db into an instance an apply changes to it, I face exceptions which are about required ProjectManager and Client.
Project currentProject = (from prj in dbContext.Projects
where prj.Id == project.Id).Single();
//---> currentProject.ProjectManagerID is null
//---> currentProject.ClientID is null
//---> currentProject.ProjectManager is present
//---> currentProject.Client is present
currentProject.Name = ....
currentProject.Progress = ....
currentProject.Status = ....
currentProject.Disabled = ....
dbContext.Entry(currentProject).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges(); //--> Validation error for required Client,ProjectManager
This is caused by the fact that when I ftech information from DB, ClientID and ProjectManagerID are null and if I set them manually as below, it will fix:
currentProject.Name = project.Name;
currentProject.Progress = project.Progress;
currentProject.Status = project.Status;
currentProject.Disabled = project.Disabled;
currentProject.ProjectManagerID = currentProject.ProjectManager.Id;
currentProject.ClientID = currentProject.Client.Id;
try
{
dbContext.Entry(currentProject).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges();
}
catch (DbEntityValidationException e)
{
addValidationErrorsToModelState(e);
return View(project);
}
I'm suspicious to virtual settings but not sure, because foreign objects are loaded but their ID is null.
P.S. I declared projects in AppDbContext as below:
public DbSet<Project> Projects { get; set; }
The problem was that I missed setter/getter for ID properties of ForeignKeys:
public class Project
{
public int Id { get; set; }
[Required]
[StringLength(100, MinimumLength = 5]
public string Name { get; set; }
[Required]
public virtual ApplicationUser Client { get; set; }
[ForeignKey("Client")]
public string ClientID{ get; set; } //<--fixed
[Required]
public virtual ApplicationUser ProjectManager { get; set; }
[ForeignKey("ProjectManager")]
public string ProjectManagerID { get; set; } //<--fixed
[Range(0,100)]
[Required]
public int Progress { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CreateDate { get; set; }
[Column("Disabled")]
public bool Disabled{ get; set; }
[Column("Status")]
public string Status{ get; set; }
}