Related
I have data class initializer
public static class ModelBuilderExtention
{
public static void Seed(this ModelBuilder modelBuilder)
{
List<Document> documents = new List<Document>()
{
new Document()
{
Id = 1,
Title = "Top Cat! The most effectual ",
Date = DateTime.Now.AddDays(-7),
UserId = "1",
FileLink = "https://sf-applications.s3.amazonaws.com/Bear/wallpapers/05/july-2020-wallpaper_desktop-3840x1600.png",
ShortDescription = "Top Cat! Who’s intellectual close friends get to " +
"call him T.C., providing it’s with dignity. " +
"Top Cat! The indisputable leader of the gang. He’s the" +
" boss, he’s a pip, he’s the championship. " +
"He’s the most tip top, Top Cat.",
Tags = new List<Tag>() {
new Tag(){ DocumentId = 1, Id = 1, TagName ="Important"},
new Tag(){ DocumentId = 1, Id = 2, TagName ="Cat"}
},
Comments = new List<Comment>() {
new Comment(){
Id = 1,
Date = DateTime.Now.AddDays(-6),
DocumentId = 1,
UserId = "1",
Content = "Ulysses, Ulysses — Soaring through all the" +
" galaxies. In search of Earth, flying in to the night" +
". Ulysses, Ulysses — Fighting evil and tyranny, with " +
"all his power, and with all of his might. "
},
new Comment(){
Id = 2,
Date = DateTime.Now.AddDays(-5),
DocumentId = 1,
UserId = "1",
Content = "Ulysses — no-one else can do the things you do" +
". Ulysses — like a bolt of thunder from the blue. Ulysses " +
"— always fighting all the evil forces bringing peace and justice to all."
} }
},
new Document()
{
Id = 2,
Title = "I never spend much time in school but",
Date = DateTime.Now.AddDays(-5),
UserId = "1",
FileLink = "https://cdn.wallpaperhub.app/cloudcache/1/b/5/8/e/f/1b58ef6e3d36a42e01992accf5c52d6eea244353.jpg",
ShortDescription = "I taught ladies plenty. It’s true I hire my body out for pay," +
" hey hey. I’ve gotten burned over Cheryl Tiegs, blown up for Raquel Welch." +
" But when I end up in the hay it’s only hay, hey hey. I might jump an open " +
"drawbridge, or Tarzan from a vine.",
Tags = new List<Tag>() {
new Tag(){ DocumentId = 2, Id = 3, TagName ="Important"},
new Tag(){ DocumentId = 2, Id = 4, TagName ="Plenty"}
},
Comments = new List<Comment>() {
new Comment(){
Id = 3,
Date = DateTime.Now.AddDays(-5),
DocumentId = 2,
UserId = "1",
Content = "Cause I’m the unknown stuntman that makes Eastwood look so fine."
},
new Comment(){
Id = 4,
Date = DateTime.Now.AddDays(-4),
DocumentId = 2,
UserId = "1",
Content = "One for all and all for one, Muskehounds are always" +
" ready. One for all and all for one, helping everybody. "
} }
},
new Document()
{
Id = 3,
Title = "One for all and all for one, it’s a pretty story.Sharing everything with fun, that’s the way to be",
Date = DateTime.Now.AddDays(-4),
UserId = "1",
FileLink = "https://i.pinimg.com/originals/f7/ae/e8/f7aee8753832af613b63e51d5f07011a.jpg",
ShortDescription = "One for all and all for one, Muskehounds are always ready. " +
"One for all and all for one, helping everybody.",
Tags = new List<Tag>() {
new Tag(){ DocumentId = 3, Id = 5, TagName ="Important"},
new Tag(){ DocumentId = 3, Id = 6, TagName ="Muskehounds"}
},
Comments = new List<Comment>() {
new Comment(){
Id = 5,
Date = DateTime.Now.AddDays(-3),
DocumentId = 3,
UserId = "1",
Content = "I never spend much time in school but I taught ladies plenty."
},
new Comment(){
Id = 6,
Date = DateTime.Now.AddDays(-3),
DocumentId = 3,
UserId = "1",
Content = "It’s true I hire my body out for pay, hey hey."
} }
}
};
List<AccessRules> accessRules = new List<AccessRules>()
{
new AccessRules()
{
Id = 1,
DocumentId = 1,
DocumentLink = "Link to document",
IsPublic = true
},
new AccessRules()
{
Id = 2,
DocumentId = 2,
DocumentLink = "Link to document",
IsPublic = true
},
new AccessRules()
{
Id = 3,
DocumentId = 3,
DocumentLink = "Link to document",
IsPublic = true
}
};
foreach (var document in documents)
{
document.AccessRulesId = accessRules[document.Id - 1].Id;
}
modelBuilder.Entity<AccessRules>().HasData(accessRules);
modelBuilder.Entity<Document>().HasData(documents);
}
}
and has 2 main entities Document
public class Document : BaseClass
{
public string Title { get; set; }
public DateTime Date { get; set; }
public string ShortDescription { get; set; }
public string FileLink { get; set; }
public List<Tag> Tags { get; set; }
public List<Comment> Comments { get; set; }
[NotMapped]
public AccessRules AccessRules { get; set; }
[ForeignKey("AccessRules")]
public int AccessRulesId { get; set; }
public string UserId { get; set; }
}
and AccessRules
public class AccessRules : BaseClass
{
[NotMapped]
public Document Document { get; set; }
[ForeignKey("DocumentId")]
public int DocumentId { get; set; }
public string DocumentLink { get; set; }
public bool IsPublic { get; set; }
}
and I get this error
The seed entity for entity type 'Document' cannot be added because it has the navigation 'Comments' set. To seed relationships, add the entity seed to 'Comment' and specify the foreign key values {'DocumentId'}.
Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values.
How I must to change entities for them to work?
It seems that in order to seed your data with a many to many relationship, you have to use ModelBuilder's fluent API like this (from comment on EntityFramewor.Docs repo):
modelBuilder.Entity<Post>()
.HasMany(p => p.Tags)
.WithMany(t => t.Posts)
.UsingEntity<Dictionary<string, object>>(
"PostTag",
r => r.HasOne<Tag>().WithMany().HasForeignKey("TagId"),
l => l.HasOne<Post>().WithMany().HasForeignKey("PostId"),
je =>
{
je.HasKey("PostId", "TagId");
je.HasData(
new { PostId = 1, TagId = "general" },
new { PostId = 1, TagId = "informative" },
new { PostId = 2, TagId = "classic" },
new { PostId = 3, TagId = "opinion" },
new { PostId = 4, TagId = "opinion" },
new { PostId = 4, TagId = "informative" });
});
It's not very intuitive, and hard to write, but it does seem to allow you to seed many:many relationships in your EF databases.
I want to fill dropdownlist countries based on User login into my application. If user is not logged on then the default country will be displayed. Please help me and guide me how to fill dropdown based on user logon country. Any help is highly appreciated.
AspUsers table -- When user register, all the information goes to this table
My LeadingClass data Model
public int? Type { get; set; }
public string Country { get; set; }
My LeadingFilterVM View Model
public int? Type { get; set; }
public IEnumerable<SelectListItem> TypeList { get; set; }
public string Country { get; set; }
public IEnumerable<SelectListItem> CountriesList { get; set; }
public IPagedList<LeadingClass> Leadings { get; set; }
My LeadingDatabaseHandle
public List<LeadingClass> LeadingBasedonFilter(int? Type, string Country = "")
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<LeadingClass> leadingClass = new List<LeadingClass>();
string sSQL;
SqlParameter[] prms = new SqlParameter[3];
sSQL = "exec GetLeeading #Type,#country";
prms[0] = new SqlParameter("#Type", SqlDbType.Int);
prms[0].Value = Sire;
prms[1] = new SqlParameter("#Country", SqlDbType.VarChar);
prms[1].Value = Country;
ds = clsUtilities.CreateCommandwithParams(sSQL, prms);
DataTable dataTable = ds.Tables[0];
foreach (DataRow dr in dataTable.Rows)
{
leadingClass.Add(
new LeadingClass
{
Id = Convert.ToInt32(dr["Id"]),
Name= Convert.ToString(dr["Name"]),
}
);
}
return leadingClass;
}
My Home Controller
[HttpGet]
public ActionResult Leading(int? type, string country,int? pageNumber)
{
LeadingDatabaseHandle leadingDatabaseHandle = new LeadingDatabaseHandle();
IEnumerable<LeadingClass> data;
if (type!=null)
{
data = leadingDatabaseHandle.LeadingBasedonFilter(type.Value, country);
}
else
{
data = leadingDatabaseHandle.LeadingSiresAll();
}
LeadingFilterVM model = new LeadingFilterVM
{
Type = type,
Country = country,
TypeList = new List<SelectListItem>
{
new SelectListItem{ Text = "General", Value = "1" },
new SelectListItem{ Text = "Advance", Value = "2" },
},
CountriesList = new List<SelectListItem>
{
new SelectListItem {Value = "NZ", Text="New Zealand" },
new SelectListItem {Value = "AUS", Text = "Australia" },
new SelectListItem {Value = "FR", Text = "France" },
new SelectListItem {Value = "GB", Text = "Great Britain" },
},
Leadings = data.ToPagedList(pageNumber ?? 1, 10)
};
return View(model);
}
My Leading View
#using (Html.BeginForm("Leading", "Home", FormMethod.Get))
{
<div class="col-sm-2">
#Html.DisplayNameFor(m => m.Leadings.FirstOrDefault().Type)
#Html.DropDownListFor(m => m.Type, Model.TypeList, new { #class = "form-control" })
</div>
<div class=" col-sm-2">
#Html.DisplayNameFor(m => m.Country)
#Html.DropDownListFor(m => m.Country, Model.CountriesList, new { #class = "form-control"})
</div>
<button type="submit" class="btn btn-info">Search</button>
}
In MVC4 razor application #Html.DropDownListFor providing selectlist using ViewBag
but how to set default value to that drop down is not getting.
#Html.DropDownListFor(m => m.SlpCode, new SelectList(ViewBag.SalesEmployee1, "Value", "Description"), new { #class = "form-control" })
for that I am tried
#Html.DropDownListFor(m => m.SlpCode, new SelectList(ViewBag.SalesEmployee1, "Value", "Description", (Model.SlpCode==-1)), new { #class = "form-control" })
but still it will not be work.
what is another solution for that?
this is what i am doing for drop down list
controller code
public ActionResult Contact()
{
Contact homeViewModel = new Contact();
homeViewModel.subject = new List<Subject>();
homeViewModel.subject.Add(new Subject { Id = 1, subject1 = "General Customer Service" });
homeViewModel.subject.Add(new Subject { Id = 2, subject1 = "Suggestions" });
homeViewModel.subject.Add(new Subject { Id = 3, subject1 = "Product Support" });
homeViewModel.Selectedid = 1; //this sets the default value for your dropdown
return View(homeViewModel);
}
Model code :
public class Contact
{ [Required(ErrorMessage="Please fill the following")]
public string name { get; set; }
[Required(ErrorMessage = "Please Enter Correct Username")]
[RegularExpression(#"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+#(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$", ErrorMessage = "Please provide valid email id")]
public string email { get; set; }
public List<Subject> subject { get; set; }
[Required(ErrorMessage="Please fill the following")]
public string message { get; set; }
public int Selectedid { get; set; }
}
View Code :
#Html.DropDownList("Selectedid", new SelectList(Model.subject, "Id", "subject1", Model.Selectedid), new { #class = "form-control", id = "subject", required = "required" })
My model is a generic List. I want to use DropDownList for foreign key property binding.
My code is
Model
public class PersonViewModel
{
public int Id { get; set; }
public string LastName{get;set;}
public int NationalityId { get; set; }
}
public class Nationality
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller
public ActionResult Index()
{
var nationalities = new List<Nationality>
{
new Nationality{Id = 0, Name = "CHOOSE NATIONALITY..."},
new Nationality{Id = 1, Name = "POLAND"},
new Nationality{Id = 2, Name = "USA"},
new Nationality{Id = 3, Name = "CANADA"}
};
var Nationalities = new SelectList(nationalities, "Id", "Name");
var persons = new List<PersonViewModel>
{
new PersonViewModel{Id = 1, LastName = "KOWALSKI", NationalityId = 1},
new PersonViewModel{Id = 1, LastName = "SMITH", NationalityId = 2},
new PersonViewModel{Id = 1, LastName = "SCHERBATSKY", NationalityId = 3}
};
ViewBag.Nationalities = Nationalities;
return View(persons);
}
View
#model List<PersonViewModel>
#Html.EditorFor(m=> Model[0].LastName)
#Html.DropDownListFor(m => Model[0].NationalityId, (SelectList)ViewBag.Nationalities)
#Html.EditorFor(m => Model[1].LastName)
#Html.DropDownListFor(m => Model[1].NationalityId, (SelectList)ViewBag.Nationalities)
#Html.EditorFor(m => Model[2].LastName)
#Html.DropDownListFor(m => Model[2].NationalityId, (SelectList)ViewBag.Nationalities)
Anyone can tell me why NationalityId property is not bound well
I can't upload image but it's not binding at all. Every DropDownList has 'CHOOSE NATIONALITY...' .
I would recommend you using Editor templates:
First - create view Shared\EditorTemplates\PersonViewModel.cshtml containing:
#model PersonViewModel
#Html.EditorFor(m => Model.LastName)
#Html.DropDownListFor(m => Model.NationalityId, (SelectList)ViewBag.Nationalities)
And in your current view
#for (int i = 0; i < Model.Count; i++)
{
#Html.EditorFor(x => Model[i])
}
Change your view model to this
public class PersonViewModel
{
public int Id { get; set; }
public string LastName{get;set;}
public int NationalityId { get; set; }
public IEnumerable<Nationality> Nationalities {get;set;}
}
In your controller
public ActionResult Index()
{
var nationalities = new List<Nationality>
{
new Nationality{Id = 0, Name = "CHOOSE NATIONALITY..."},
new Nationality{Id = 1, Name = "POLAND"},
new Nationality{Id = 2, Name = "USA"},
new Nationality{Id = 3, Name = "CANADA"}
};
var nationalities = new SelectList(nationalities, "Id", "Name");
var persons = new List<PersonViewModel>
{
new PersonViewModel{Id = 1, LastName = "KOWALSKI", NationalityId = 1 , Nationalities = nationalities},
new PersonViewModel{Id = 1, LastName = "SMITH", NationalityId = 2, Nationalities = nationalities},
new PersonViewModel{Id = 1, LastName = "SCHERBATSKY", NationalityId = 3, Nationalities = nationalities}
};
return View(persons);
}
And in your view
#model List<PersonViewModel>
#Html.EditorFor(m => m[0].LastName)
#Html.DropDownListFor(m => m[0].NationalityId, Model[0].Nationalities)
#Html.EditorFor(m => m[1].LastName)
#Html.DropDownListFor(m => m[1].NationalityId, Model[1].Nationalities)
#Html.EditorFor(m => m[2].LastName)
#Html.DropDownListFor(m => m[2].NationalityId, Model[2].Nationalities)
Two things:
Each dropdown needs its own select list. Currently you are using the same select list for each dropdown.
You need to specify a selected value for each select list, like so:
new SelectList(nationalities, "Id", "Name", persons[0].NationalityId);
I am attempting to structure my database appropriately for my web application. I am unsure the correct way to proceed with the keys and relationships. Basically..
My project contains a Product
Which can contain many Reports, however, the same Report can not relate to multiple Products.
I have Users, which may have many reports available to them.. regardless of the reports parent product.
My structure thus far
public class Product
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class Report
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual Product Product { get; set; }
}
public class User
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Report> Reports { get; set; }
}
And to Seed
protected override void Seed(Insight.Data.InsightDb context)
{
context.Products.AddOrUpdate(p => p.ProductID,
new Product { ProductName = "Product 1" },
new Product { ProductName = "Product 2" }
);
context.Reports.AddOrUpdate(p => p.ReportID,
new Report { ReportName = "Report A", ProductID = 1, },
new Report { ReportName = "Report B", ProductID = 1, },
new Report { ReportName = "Report C", ProductID = 1, },
new Report { ReportName = "Report D", ProductID = 2, },
new Report { ReportName = "Report E", ProductID = 2, }
);
context.Users.AddOrUpdate(u => u.UserID,
new User { FirstName = "Frank", LastName = "Reynolds", },
new User { FirstName = "Dee", LastName = "Reyonolds", }
);
}
I am unsure how to properly assign the Reports to the Users, or even know if I am on the right track. Also, is there a better practice than using int as a key?
While I haven't used the approach you have above.. here's my stab at it:
protected override void Seed(Insight.Data.InsightDb context)
{
var product1 = new Product{ Name = "Product 1"};
var product2 = new Product{ Name = "Product 2"};
var reports1 = new List<Report>
{
new Report { Name = "Report A", Product = product1, },
new Report { Name = "Report B", Product = product1, },
new Report { Name = "Report C", Product = product1, },
new Report { Name = "Report D", Product = product2, },
new Report { Name = "Report E", Product = product2, }
};
context.Products.AddOrUpdate(p => p.ProductID,
product1,
product2
);
context.Reports.AddOrUpdate(p => p.ReportID,
reports1
);
context.Users.AddOrUpdate(u => u.UserID,
new User { FirstName = "Frank", LastName = "Reynolds", Reports = reports1 },
new User { FirstName = "Dee", LastName = "Reyonolds" },
);
}
I'm just not sure if setting up the reports part is correct (adding a list to the AddOrUpdate function), so that's something you may have to look in to if this doesn't work.
I have found a solution. It turns out I was interested in a many-to-many relationship, with a bridge table in between Reports and Users. These are my entities to establish this relationship.
public class Report
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual Product Product { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class User
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Report> Reports { get; set; }
}
Then to populate my data with a code first approach
protected override void Seed(Insight.Data.InsightDb context)
{
Product product1 = new Product { Name = "Product 1" };
Product product2 = new Product { Name = "Product 2" };
Report reportA = new Report { Name = "Report A", Product = product1 };
Report reportB = new Report { Name = "Report B", Product = product1 };
Report reportC = new Report { Name = "Report C", Product = product1 };
Report reportD = new Report { Name = "Report D", Product = product2 };
Report reportE = new Report { Name = "Report E", Product = product2 };
List<User> users = new List<User>();
users.Add(new User { FirstName = "Dee", LastName = "Reynolds", Reports = new List<Report>() { reportA, reportB, reportC } });
users.Add(new User { FirstName = "Frank", LastName = "Reynolds", Reports = new List<Report>() { reportC, reportD, reportE } });
users.ForEach(b => context.Users.Add(b));
}