entity framework many to many inserts code first - asp.net-mvc

this is my model
public class Post
{
public long PostID { get; set; }
[Required]
[MaxLength(255)]
public string Title { get; set; }
}
public class Tag
{
public long TagID { get; set; }
[Required]
[Display(Name = "Tag Name")]
[MaxLength(30)]
public string TagName { get; set; }
public bool IsActive { get; set; }
}
public class TagPost
{
public long TagPostID { get; set; }
public long PostID { get; set; }
public long TagID { get; set; }
[ForeignKey("PostID")]
public virtual Post Posts { get; set; }
[ForeignKey("TagID")]
public virtual Tag Tags { get; set; }
}
1) Is this the right many to many configuration in EF 4.1 without mentioning the modelbinder for many to many.
2) if i have completed the many to many configuration using dataannotation why the data is not inserting in tagpost .
public void InsertPostQuestion(Post post,List<string> tags)
{
context.Posts.Add(post);
foreach (string tag in tags)
{
Tag tagr = new Tag();
tagr.TagName = tag;
tagr.IsActive = true;
context.Tags.Add(tagr);
}
context.SaveChanges();
}
3) I do have to define modelbinder to have many to many inserts or delete or update?
modelBuilder.Entity<Post>().
HasMany(c => c.Tags).
WithMany(p => p.Posts).
Map(
m =>
{
m.MapLeftKey("PostID");
m.MapRightKey("TagID");
m.ToTable("TagPost");
});

Change your models to this:
public class Post
{
public long PostID { get; set; }
[Required]
[MaxLength(255)]
public string Title { get; set; }
public bool IsActive { get; set; }
public virtual List<Tag> Tags { get; set; }
}
public class Tag
{
public long TagID { get; set; }
[Required]
[Display(Name = "Tag Name")]
[MaxLength(30)]
public string TagName { get; set; }
public bool IsActive { get; set; }
public virtual List<Post> Posts { get; set; }
}
and then save like so:
public void InsertPostQuestion(Post post,List<string> tags)
{
context.Posts.Add(post);
foreach (string tag in tags)
{
// TODO: If tag has a unique index on TagName, see if it exists first
Tag tagr = new Tag();
tagr.TagName = tag;
tagr.IsActive = true;
context.Tags.Add(tagr);
post.Tags.Add(tagr);
}
context.SaveChanges();
}
EF will create the intermediate table in the db and populate it nicely automatically.

Related

NullReferenceException in a three table model in Entity Framework

I'm trying to join three tables in a view model. It works with two tables but crashes when I add a third. Here are the models and the controller. The models section_detail, phone, and department were generated by Entity Framework.
EmployeeViewModel was created by copying properties from the other models. I've abbreviated some of the models shown here with:
public partial class section_detail
{
public int section_detail_id { get; set; }
public Nullable<int> parent_section_det_id { get; set; }
. . .
public string Comments { get; set; }
public string email { get; set; }
public virtual department department { get; set; }
public virtual phone phone { get; set; }
}
public partial class phone
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public phone()
{
this.section_detail = new HashSet<section_detail>();
}
public int phone_id { get; set; }
public string area_code { get; set; }
public string phone_nbr { get; set; }
. . .
public string activity_code { get; set; }
public string function_code { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<section_detail> section_detail { get; set; }
public virtual BudgetUnit BudgetUnit { get; set; }
}
public partial class department
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public department()
{
this.section_detail = new HashSet<section_detail>();
}
public int dept_id { get; set; }
public string description { get; set; }
public string cost_center_code { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<section_detail> section_detail { get; set; }
}
public class EmployeeViewModel
{
public int section_detail_id { get; set; }
public Nullable<int> parent_section_det_id { get; set; }
public Nullable<byte> page_code { get; set; }
public string cost_center_code { get; set; }
public string print_descrip { get; set; }
public Nullable<int> phone_id { get; set; }
public Nullable<int> employee_id { get; set; }
public static explicit operator EmployeeViewModel(List<section_detail> v)
{
throw new NotImplementedException();
}
public string first_name { get; set; }
. . .
public string Comments { get; set; }
public string email { get; set; }
public string description { get; set; }
public string area_code { get; set; }
public string phone_nbr { get; set; }
public string BU { get; set; }
}
Controller:
private vcpds_test1Entities db = new vcpds_test1Entities();
// GET: EmployeeList
public ActionResult Index()
{
List<section_detail> employeeList = db.section_detail.ToList();
List<EmployeeViewModel> employeeVMList = employeeList.Where(emp => emp.page_code == 3)
.Select(emp => new EmployeeViewModel
{
last_name = emp.last_name,
first_name = emp.first_name,
employee_id = emp.employee_id,
phone_nbr = "(" + emp.phone.area_code + ") " + emp.phone.phone_nbr.Substring(0, 3) + "-" + emp.phone.phone_nbr.Substring(3, 4),
BU = emp.phone.BU,
description = emp.department.description,
page_code = emp.page_code
}).OrderBy(emp => emp.last_name).ThenBy(emp => emp.first_name).ToList();
return View(employeeVMList);
}
I get these messages:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
VCPDS2.Models.section_detail.department.get returned null.
If I comment out description = emp.department.description from the controller, then it will return data from the section_detail and phone tables. I've checked the database and the relationships seem ok. I've tried refreshing the models from the database with no change.
It's possible that a emp doesn't have a department so it in itself is null. Description can't be a property of a null. So, what you can simply do is check if it is null first by using null operator:
...
//description = emp.department.description,
description = emp.department?.description ?? "",
...
Basically, if department itself is null, it will stop checking right there, and the ?? shortcut is to use the statement on the right side which is "" if the statement on the left is null.
If you were not expecting an emp not to have a department, you may need to revise your query
Quick edit: You probably need to use an Include in your query so it can bring the department's properties (for description):
List<section_detail> employeeList = db.section_detail
.Include(x => x.department)
.ToList();

ASP.NET MVC Check if User has already posted in this table

I'm gonna cut to the chase.
I'm creating a Survey platform, it has 3 models.
Model Survey, it has Many SurveyQuestion which has many SurveyAnswer.
(I can insert all of the values of these models but I dont think it is needed)
public class SurveyAnswer
{
[Key]
public int Id { get; set; }
public string Value { get; set; }
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
public int QuestionId { get; set; }
public virtual Survey Survey { get; set; }
public virtual SurveyQuestion Question { get; set; }
public string Comment { get; set; }
}
Now a problem I'm having is once someone created a survey and another person is starting it, he answers and that's it. How do I show that the next time he comes to an index page? How do I show that "you already submitted this survey"? Do I do that in Controller or in View? I would prefer to that in this action currently (it's a menu for all ongoing surveys).
[HttpGet]
public ActionResult Menu()
{
var survey = Mapper.Map<IEnumerable<Survey>, IEnumerable<SurveyViewModel>>(_unitOfWork.SurveyRepository.Get());
return View(survey.ToList());
}
Put all your validation rules to your AbstractValidator class.
[Validator(typeof(SurveyAnswerValidator))]
public class SurveyAnswer{
[Key]
public int Id { get; set; }
public string Value { get; set; }
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
public int QuestionId { get; set; }
public virtual Survey Survey { get; set; }
public virtual SurveyQuestion Question { get; set; }
public string Comment { get; set; }
}
public class SurveyAnswerValidator : AbstractValidator<SurveyAnswer>
{
public SurveyAnswerValidator()
{
//list your rules
RuleFor(x => x.SubmittedBy).Must(BeUnique).WithMessage("Already
submitted this survey");
}
private bool BeUnique(string submittedBy)
{
if(_context.SurveyAnswers.
FirstOrDefault(x => x.SubmittedBy == submittedBy) == null){
return true;
}
else{
return false;
}
}
}
If you want to check uniqueness in ViewModel you can use Remote.
public class SurveyAnswerVM{
[Key]
public int Id { get; set; }
public string Value { get; set; }
[Remote("HasSubmitted", "ControllerName")]
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
public int QuestionId { get; set; }
public virtual Survey Survey { get; set; }
public virtual SurveyQuestion Question { get; set; }
public string Comment { get; set; }
}
Where HasSubmitted is a method you may create in controller to return true if the user has submitted.
RemoteAttribute
https://msdn.microsoft.com/en-us/library/gg508808(VS.98).aspx
The best solution by vahdet (suggested in comments)
[Index("IX_AnswerQuestion", 2, IsUnique = true)]
[StringLength(36)]
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
[Index("IX_AnswerQuestion", 1, IsUnique = true)]
public int QuestionId { get; set; }

ViewModel for multiple tables without links between tables

I'm trying to write a View Model in an ASP.NET MVC5 project to show data from different tables on a form that the user can then edit and save. I'm using the following :-
VS 2017, c#, MySQL Database, Entity Framework 6.1.3, MySQL Connector 6.9.9, Code First from Database (existing database that I can't change)
To complicate matters, there are no links between the tables in the database, so I cannot work out how to create a suitable View Model that will then allow me to save the changes.
Here are the 4 table models :-
public partial class evc_bearer
{
[Key]
[Column(Order = 0]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long evcid { get; set; }
[Key]
[Column(Order = 1]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long bearerid { get; set; }
public int vlan { get; set; }
[Column("ref")]
public string _ref { get; set; }
[Required]
public string port { get; set; }
[Required]
public string endpoint { get; set; }
}
public partial class bearer
{
[Key]
public long id { get; set; }
[Column("ref")]
[Required]
public string _ref { get; set; }
public string name { get; set; }
public long? site { get; set; }
public long? provider { get; set; }
public long? mtu { get; set; }
public float? rental { get; set; }
public int? offsiteprovider { get; set; }
public float? offsiteproviderrental { get; set; }
public bool? aend { get; set; }
public int? equipmentport { get; set; }
public string orderref { get; set; }
public string offsiteref { get; set; }
public string notes { get; set; }
public float? bookingfactor { get; set; }
}
public partial class evc
{
[Key]
public long id { get; set; }
[Required]
public string type { get; set; }
public byte servicetype { get; set; }
public byte cos { get; set; }
public int cir { get; set; }
public int pir { get; set; }
public bool burst { get; set; }
[Column("ref")]
public string _ref { get; set; }
public string orderref { get; set; }
public byte state { get; set; }
public string notes { get; set; }
public float? rental { get; set; }
}
public partial class evc_provider
{
[Key]
public long id { get; set; }
[Required]
public string provider { get; set; }
}
This is the View Model I tried writing :-
public partial class evcBearersVM
{
[Key]
[Column(Order = 0)]
public long evcid { get; set; }
[Key]
[Column(Order = 1)]
public long id { get; set; }
[Column("ref")]
public string b_ref { get; set; }
public string b_name { get; set; }
public string ep_provider { get; set; }
public int eb_vlan { get; set; }
public string eb_port { get; set; }
public string eb_endpoint { get; set; }
}
This is the Linq query I used to populate the View Model :-
IQueryable<evcBearersVM> data = from eb in csdb.evc_bearers
join b in csdb.bearers on eb.bearerid equals b.id
join ep in csdb.evc_providers on b.provider equals ep.id
join e in csdb.evcs on eb.evcid equals e.id
where (eb.evcid == evcid && b.id == id)
select new evcBearersVM
{
evcid = eb.evcid,
id = b.id,
b_ref = b._ref,
b_name = b.name,
ep_provider = ep.provider,
eb_vlan = eb.vlan,
eb_port = eb.port,
eb_endpoint = eb._ref
};
So the query works and joins the tables to get the data I need and I can display this date in various views as needed. What I now need to do is be able to edit a row and save it back to the database. I have an Edit View that is showing the data I need but I'm not sure how to save changes given that it's a View Model and the DB Context isn't aware of it. Grateful for any help.
What you should do is, use the same view model as your HttpPost action method parameter and inside the action method, read the entities you want to udpate using the Id's (you can get this from the view model, assuming your form is submitting those) and update only those properties you need to update.
[HttpPost]
public ActionResult Edit(evcBearersVM model)
{
var b = csdb.bearers.FirstOrDefault(a=>a.id==model.id);
if(b!=null)
{
b.name = model.b_name;
b._ref = model.b_ref;
csdb.SaveChanges();
}
// Update the other entity as well.
return RedirectToAction("Index");
}

asp.net using mvc 3 linq and join

i have a problem with my join in my asp.net .. i have two database tables.. named APPLICANT and Profile...they have the same fields.. meaning if the Last name in applicant is null the last name is already in profile table. I already connect my program to the applicant table.. but it have so many null fields that have to fetch from the profile data table.... sorry i'm new in asp.net ...
Here's my code in controller:
public View Result Index()
{
var applicants = (from a in db.APPLICANTs
select a).ToList();
return View(applicants);
}
heres my context:
public partial class APPLICANT
{
public int APPLICANT_ID { get; set; }
public Nullable<int> Profile_id { get; set; }
public string APPLICANT_LastName { get; set; }
public string APPLICANT_FirstName { get; set; }
public string APPLICANT_MiddleName { get; set; }
public string APPLICANT_Address { get; set; }
public string APPLICANT_City { get; set; }
public string APPLICANT_ZipCode { get; set; }
public string APPLICANT_Phone { get; set; }
public string APPLICANT_Email { get; set; }
}
public partial class Profile
{
public int PROFILE_ID { get; set; }
public string Applicant_LASTNAME { get; set; }
public string Applicant_FIRSTNAME { get; set; }
public string Applicant_MIDDLENAME { get; set; }
public string Applicant_EMAIL { get; set; }
public string Applicant_PHONE { get; set; }
public string Applicant_ADDRESS { get; set; }
public string Applicant_ZIPCODE { get; set; }
public string Applicant_CITY { get; set; }
}
thanks for those who can help my problem..

PagedList in MVC3 with IQueryable

I can't understand what i'm doing wrong. Every time I'm getting this error:
The entity or complex type 'BusinessLogic.CompanyWithDivisionCount' cannot be constructed in a LINQ to Entities query.
I need to get info from 'Company' table and divisions count of each company from 'Division' table, and then make PagedList. Here is my 'Company' table:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using BusinessLogic.Services;
using BusinessLogic.Models.ValidationAttributes;
namespace BusinessLogic.Models
{
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
}
Here is my domain model:
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
public class CompanyWithDivisionCount: Company // I'm using this
{
public int DivisionCount { get; set; }
}
Here is my controller:
public ActionResult CompaniesList(int? page)
{
var pageNumber = page ?? 1;
var companies = companyService.GetCompaniesWithDivisionsCount2();
var model = companies.ToPagedList(pageNumber, PageSize);
return View(model);
}
And here is my service part:
public IQueryable<CompanyWithDivisionCount> GetCompaniesWithDivisionsCount2()
{
return (from c in dataContext.Companies.AsQueryable()
select new CompanyWithDivisionCount
{
Id = c.Id,
Name = c.Name,
Status = c.Status,
EffectiveDate = c.EffectiveDate,
URL = c.URL,
EAP = c.EAP,
EAPCredentials = c.EAPCredentials,
Comments = c.Comments,
DivisionCount = (int)dataContext.Divisions.Where(b => b.CompanyName == c.Name).Count()
});
}
}
Thanks for help!!!
Creator of PagedList here. This has nothing to do with PagedList, but rather is an Entity Framework issue (I'm no expert on Entity Framework, so can't help you there). To confirm that this is true, write a unit test along the following lines:
[Test]
public void ShouldNotThrowAnException()
{
//arrange
var companies = companyService.GetCompaniesWithDivisionsCount2();
//act
var result = companies.ToList();
//assert
//if this line is reached, we win! no exception on call to .ToList()
}
I would consider changing you data model if possible so that instead of relating Companies to Divisions by name strings, instead use a properly maintained foreign key relationship between the two objects (Divisions should contain a CompanyID foreign key). This has a number of benefits (including performance and data integrity) and will almost certainly make your life easier moving forward if you need to make further changes to you app (or if any company ever decides that it may re-brand it's name).
If you create a proper foreign key relationship then your domain model could look like
public class Company
{
...
public virtual ICollection<Division> Divisions{ get; set; }
public int DivisionCount
{
get
{
return this.Divisions.Count()
}
}
...
}

Resources