I'm new to Entity Framework, which I'm using for an ASP.NET MVC4 project. I'm trying to create a foreign key relationship and am not having much success. The problem may be in my seed data, which I'm not sure how to restructure from an earlier attempt to get this working.
Here are my two classes:
public class HardwareType
{
public int Id { get; set; }
[Required]
[StringLength(128)]
public string HType { get; set; }
public int HardwareId { get; set; }
public virtual Hardware Hardware { get; set; }
}
and
public class Hardware
{
public int Id { get; set; }
//public int HardwareId { get; set; }
...
public virtual ICollection<HardwareType> HardwareType { get; set; }
}
Here is my sample seed data:
protected override void Seed(Context context)
{
var loc = new List<Location> {
new Location { LocationName = "Paradise Lane" },
new Location { LocationName = "81st Street" }
};
loc.ForEach(l => context.Locations.Add(l));
var type = new List<SoftwareType> {
new SoftwareType { SType = "Suite" }
};
type.ForEach(t => context.SoftwareTypes.Add(t));
var pub = new List<SoftwarePublisher> {
new SoftwarePublisher { Publisher = "Adobe" },
new SoftwarePublisher { Publisher = "Apple" },
new SoftwarePublisher { Publisher = "Microsoft" }
};
var soft = new List<Software> {
new Software { Title = "Adobe Creative Suite", Version = "CS6", SerialNumber = "1234634543", Platform = "Mac", Notes = "Macs rock!", PurchaseDate = "2012-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 0, Locations = loc.Where(s => s.LocationName == "Paradise Lane").ToArray(), Types = type.Where(s => s.SType == "Suite").ToArray(), Publishers = pub.Where(s => s.Publisher == "Adobe").ToArray() },
new Software { Title = "Microsoft Office", Version = "2012", SerialNumber = "34252345", Platform = "PC", Notes = "PCs stink!", PurchaseDate = "2012-11-04", Suite = true, SubscriptionEndDate = null, SeatCount = 0, Locations = loc.Where(s => s.LocationName == "81st Street").ToArray(), Types = type.Where(s => s.SType == "Suite").ToArray(), Publishers = pub.Where(s => s.Publisher == "Microsoft").ToArray() },
new Software { Title = "Apple iLife", Version = "2012", SerialNumber = "54675747564", Platform = "Mac", Notes = "Macs still rock!", PurchaseDate = "2012-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 0, Locations = loc.Where(s => s.LocationName == "Paradise Lane").ToArray(), Types = type.Where(s => s.SType == "Suite").ToArray(), Publishers = pub.Where(s => s.Publisher == "Apple").ToArray() }
};
soft.ForEach(s => context.Software.Add(s));
var manuf = new List<Manufacturer> {
new Manufacturer { ManufacturerName = "SonicWall" },
new Manufacturer { ManufacturerName = "Cisco" },
new Manufacturer { ManufacturerName = "Barracuda" },
new Manufacturer { ManufacturerName = "Dell" },
new Manufacturer { ManufacturerName = "HP" },
new Manufacturer { ManufacturerName = "Maxtor" },
new Manufacturer { ManufacturerName = "LaCie" },
new Manufacturer { ManufacturerName = "APC" },
new Manufacturer { ManufacturerName = "Intel" },
new Manufacturer { ManufacturerName = "D-Link" },
new Manufacturer { ManufacturerName = "Western Digital" },
new Manufacturer { ManufacturerName = "Quantum" },
new Manufacturer { ManufacturerName = "Seagate" },
new Manufacturer { ManufacturerName = "Apple" },
new Manufacturer { ManufacturerName = "Canon" },
};
var device = new List<DeviceType> {
new DeviceType { DType = "Network Device"},
new DeviceType { DType = "Other"}
};
var htype = new List<HardwareType> {
new HardwareType { HType = "PC" },
new HardwareType { HType = "Monitor" },
new HardwareType { HType = "Printer" },
new HardwareType { HType = "Miscellaneous" }
};
var hard = new List<Hardware> {
new Hardware { AssetTagId = "2134", Type = device.Where(h => h.DType == "Network Device").ToArray(), Manufacturer = manuf.Where(h => h.ManufacturerName == "SonicWall").ToArray(), ServiceTagId = "5243", SerialNumber = "3456", ProductNumber = "2345", PurchaseDate = "2012-10-23", WarrantyExpiration = "2012-11-12", WarrantyType = "NBD", Location = loc.Where(h => h.LocationName == "Paradise Lane").ToArray(), Notes = "Scrapped", HardwareType = htype.Where(h => h.HType == "Monitor").ToArray()},
new Hardware { AssetTagId = "2134", Type = device.Where(h => h.DType == "Network Device").ToArray(), Manufacturer = manuf.Where(h => h.ManufacturerName == "SonicWall").ToArray(), ServiceTagId = "5243", SerialNumber = "3456", ProductNumber = "2345", PurchaseDate = "2012-10-23", WarrantyExpiration = "2012-11-12", WarrantyType = "NBD", Location = loc.Where(h => h.LocationName == "Paradise Lane").ToArray(), Notes = "Scrapped", HardwareType = htype.Where(h => h.HType == "PC").ToArray() },
new Hardware { AssetTagId = "2134", Type = device.Where(h => h.DType == "Network Device").ToArray(), Manufacturer = manuf.Where(h => h.ManufacturerName == "SonicWall").ToArray(), ServiceTagId = "5243", SerialNumber = "3456", ProductNumber = "2345", PurchaseDate = "2012-10-23", WarrantyExpiration = "2012-11-12", WarrantyType = "NBD", Location = loc.Where(h => h.LocationName == "Paradise Lane").ToArray(), Notes = "Scrapped", HardwareType = htype.Where(h => h.HType == "PC").ToArray() }
};
hard.ForEach(h => context.Hardwares.Add(h));
base.Seed(context);
}
How do I structure this so the foreign key relationship works. Right now, I get this error: Unable to set field/property HardwareType on entity type CIT.Models.Hardware. See InnerException for details.
The inner exception is: An item cannot be removed from a fixed size Array of type 'CIT.Models.HardwareType[]'.
try changing you'r tables structure like this :
public class Hardware
{
public int Id { get; set; }
.
.
.
public HardwareTypeId { get; set; }
public virtual HardwareType hardwareType {get;set;}
}
and HardwareType :
public class HardwareType
{
public int Id { get; set; }
public string TypeName {get;set;}
}
Related
Here i have a problem with data table to convert json. This is my class called SearchCollection
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public int ClassGroupId { get; set; }
public string ClassName { get; set; }
public int ClassNumber { get; set; }
public int BookTypeId { get; set; }
public string BookType { get; set; }
I have collected a data from store procedure and pushed into the datatable, thats why am using ConvertToDatatable(), that time i got a datatable which contains 3 tables data
static DataTable ConvertToDatatable(IEnumerable<SearchCollection> list)
{
var dt = new DataTable();
dt.Columns.Add("CategoryId");
dt.Columns.Add("CategoryName");
dt.Columns.Add("ClassGroupId");
dt.Columns.Add("ClassName");
dt.Columns.Add("ClassNumber");
dt.Columns.Add("BookTypeId");
dt.Columns.Add("BookType");
foreach (var item in list)
{
var row = dt.NewRow();
row["CategoryId"] = item.CategoryId;
row["CategoryName"] = item.CategoryName;
row["ClassGroupId"] = item.ClassGroupId;
row["ClassName"] = item.ClassName;
row["ClassNumber"] = item.ClassNumber;
row["BookTypeId"] = item.BookTypeId;
row["BookType"] = item.BookType;
dt.Rows.Add(row);
}
return dt;
}
this contain 3 tables data.
So.. this is have tried to group the data, but here am getting the answer like category on top inside category shows booktype and inside booktype shows list of classnames, but i want 3 set of data
category {},booktype{},classnames{}
var result = rows.GroupBy(r => new { x = r["CategoryId"], y = r["CategoryName"] }).Select(g => new
{
CategoryId = g.Key.x,
CategoryName = g.Key.y,
BookTypes = g.GroupBy(r => new { h = r["BookTypeId"], i = r["BookType"] }).Select(g1 => new
{
BookTypeId = g1.Key.h,
BookType = g1.Key.i,
ClassNames = g1.Select(r => new
{
ClassGroupId = r["ClassGroupId"],
ClassName = r["ClassName"],
ClassNumber = r["ClassNumber"]
}),
}),
});
Rusult
This is my result
{ CategoryId:1 CategoryName:CD ClassGroupId:15 ClassName:I ClassNumber:1 BookTypeId:1 BookType:General CD}
{ CategoryId:2 CategoryName:DVD ClassGroupId:16 ClassName:II ClassNumber:2 BookTypeId:2 BookType:General DVD}
{ CategoryId:3 CategoryName:Book ClassGroupId:17 ClassName:III ClassNumber:3 BookTypeId:3 BookType:General Books}
But i want the result like this
+ Category={ CategoryId:1 CategoryName:CD
CategoryId:2 CategoryName:DVD
CategoryId:3 CategoryName:Book }
ClassGroup={ClassGroupId:15 ClassName:I ClassNumber:1
ClassGroupId:16 ClassName:II ClassNumber:2
ClassGroupId:17 ClassName:III ClassNumber:3}
BookType{ BookTypeId:1 BookType:General CD
BookTypeId:2 BookType:General DVD
BookTypeId:3 BookType:General Books
}
here my result is booktype is under category and classname under booktype. but i want the result just like 3 groups of records in single json, any one help just like category grouped collection, class grouped collection and book type collection in single json data.
Is this what you're looking for?
var result = new
{
Category = rows
.GroupBy(r => new
{
x = r["CategoryId"],
y = r["CategoryName"]
})
.Select(g => new
{
CategoryId = g.Key.x,
CategoryName = g.Key.y
}),
ClassGroup = rows
.GroupBy(r => new
{
x = r["ClassGroupId"],
y = r["ClassName"],
z = r["ClassNumber"]
})
.Select(g => new
{
ClassGroupId = g.Key.x,
ClassName = g.Key.y,
ClassNumber = g.Key.z
}),
BookType = rows
.GroupBy(r => new
{
x = r["BookTypeId"],
y = r["BookType"]
})
.Select(g => new
{
BookTypeId = g.Key.x,
BookType = g.Key.y
})
};
Fiddle: https://dotnetfiddle.net/h9qXqc
I encountered a problem with popup control inside modal edit form of the gridview.
the problem is: popup control won't hide when i click on modal form context area! it just reordered.
please see attached movie first then read the code.
thanks.
here is my code:
MODEL:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public int Avg { get; set; }
}
CONTROLLER:
public class HomeController : Controller
{
public ActionResult Index()
{
Session["Students"] = new List<Student>()
{
new Student { Id = 1, Name = "N1", Family = "f1", Avg = 1 } ,
new Student { Id = 2, Name = "N2", Family = "f2", Avg = 2 } ,
new Student { Id = 3, Name = "N3", Family = "f3", Avg = 3 } ,
new Student { Id = 4, Name = "N4", Family = "f4", Avg = 4 } ,
};
return View(Session["Students"]);
}
public ActionResult PartialGridView(Student student)
{
return PartialView("Index", Session["Students"]);
}
}
View
#model List<Test.Models.Student>
#Html.DevExpress().GridView(settings =>
{
settings.Name = "GvStudent";
settings.KeyFieldName = "Id";
settings.CallbackRouteValues = new { Controller = "Home", Action = "PartialGridView" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "AddStudentPartialGridView" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "UpdateStudentPartialGridView" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "DeleteStudentPartialGridView" };
settings.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm;
settings.SettingsPopup.EditForm.Modal = true;
settings.SettingsPopup.EditForm.HorizontalAlign = PopupHorizontalAlign.WindowCenter;
settings.SettingsPopup.EditForm.VerticalAlign = PopupVerticalAlign.WindowCenter;
settings.SettingsPopup.EditForm.Width = 400;
settings.SettingsPopup.EditForm.Height = 200;
settings.SettingsText.PopupEditFormCaption = "Student";
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.Columns.Add(Name =>
{
Name.FieldName = "Name";
});
settings.Columns.Add(Family =>
{
Family.FieldName = "Family";
});
settings.Columns.Add(Avg =>
{
Avg.FieldName = "Avg";
});
settings.SetEditFormTemplateContent(content =>
{
Html.DevExpress().Button(btnShow =>
{
btnShow.Name="btnShow";
btnShow.ClientSideEvents.Click = "function(s, e){popupControl.ShowAtElement(document.getElementById(s.name));}";
}).Render();
});
}).Bind(Model).GetHtml()
#{
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "popupControl";
settings.CloseAction = CloseAction.OuterMouseClick;
settings.PopupVerticalAlign = PopupVerticalAlign.Below;
settings.PopupHorizontalAlign = PopupHorizontalAlign.LeftSides;
settings.ShowHeader = false;
settings.ShowFooter = false;
settings.AllowDragging = false;
settings.AutoUpdatePosition = true;
settings.Width = 320;
settings.SetContent(() =>
{
ViewContext.Writer.Write("hello world!");
});
}).GetHtml();
}
I'm trying to return a result from a list with a Linq method but i get an error saying that I "implictly can't convert my class to generic list. I'm using Get... method.
Would very much appreciate if someone could help me out with this.
This is my Tamagotchi class:
public class Tamagotchi
{
public string Name { get; set; }
public DateTime Born { get; set; }
public int Health { get; set; }
}
This is the API:
public class SomeController : ApiController
{
List<Tamagotchi> Gotchis = new List<Tamagotchi>
{
new Tamagotchi { Born = DateTime.Now.AddYears(-5), Health = 30, Name = "XTP" },
new Tamagotchi { Born = DateTime.Now.AddYears(-4), Health = 49, Name = "ZQX" },
new Tamagotchi { Born = DateTime.Now.AddYears(-3), Health = 15, Name = "VBR" },
new Tamagotchi { Born = DateTime.Now.AddYears(-2), Health = 87, Name = "BNQP" },
new Tamagotchi { Born = DateTime.Now.AddYears(-1), Health = 62, Name = "VLW" },
};
public IEnumerable<Tamagotchi> Get2()
{
var _result = Gotchis.SingleOrDefault(tama => tama.Name == "VLW");
return _result;
}
}
Thank you!
/Chris
SingleOrDefault will return a single Tamagutchi, so the result is not an IEnumerable at all. Perhaps you mean
public Tamagotchi Get2()
{
var _result = Gotchis.SingleOrDefault(tama => tama.Name == "VLW");
return _result;
}
or
public IEnumerable<Tamagotchi> Get2()
{
var _result = Gotchis.Where(tama => tama.Name == "VLW");
return _result;
}
I have three models (Applicant, Meeting, City) and I joined three of them. I want to get Count by grouping MeetingId in Applicant model. Here are my models and method I use for populating Dropdownlist in Controller. So, like the "Expired" property in the Controller, how can I obtain the count for the MeetingId by grouping on "TotalMeetingById" property?
Applicant Model:
public class Applicant
{
public int ApplicantID { get; set; }
public DateTime? SubmitDate { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int MeetingId { get; set; }
}
Meeting Model:
public class Meeting
{
public int MeetingID { get; set; }
public string MeetingName { get; set; }
public DateTime MeetingStartDate { get; set; }
public DateTime? MeetingEndDate { get; set; }
public int? TotalParticipant { get; set; }
public int? MeetingCityId { get; set; }
public int? ParticipantCityAId { get; set; }
public int? ParticipantCityBId { get; set; }
}
City Model:
public class City
{
public int CityID { get; set; }
public string CityName { get; set; }
}
Controller:
private void PopulateDropDownList()
{
var meetingsQuery = repository.Meetings
.GroupJoin(repository.Cities, m => m.MeetingCityId, c => c.CityID, (m, c) => new { m, cA = c.DefaultIfEmpty() })
.SelectMany(z => z.cA.Select(cA => new { m = z.m, cA }))
.GroupJoin(repository.Cities, m => m.m.ParticipantCityAId, c => c.CityID, (m, c) => new { m.m, m.cA, cB = c.DefaultIfEmpty() })
.SelectMany(w => w.cB.Select(cB => new { m = w.m, cA = w.cA, cB }))
.GroupJoin(repository.Cities, m => m.m.ParticipantCityBId, c => c.CityID, (m, c) => new { m.m, m.cA, m.cB, cC = c.DefaultIfEmpty() })
.SelectMany(t => t.cC.Select(cC => new { m = t.m, cA = t.cA, cB = t.cB, cC }))
.Select(
m =>
new
{
CityID = m.cA.CityID,
CityName = m.cA.CityName,
MeetingDate = m.m.MeetingStartDate,
MeetingName = m.m.MeetingName,
NameofMeetingCityIdA = m.cA != null ? m.cA.CityName : null,
NameofMeetingCityIdB = m.cB != null ? m.cB.CityName : null,
NameofMeetingCityIdC = m.cC != null ? m.cC.CityName : null
})
.OrderBy(x => x.CityID)
.AsEnumerable()
.Select(
i => new
{
Value = i.CityID.ToString(),
DisplayValue = string.Format("{0} ({1:dd MMMM yyyy})", i.NameofMeetingCityIdA, i.MeetingDate),
Expired = i.MeetingDate < DateTime.UtcNow,
TotalMeetingById= ??? >>> I cannot get the total count for the related MeetingId at here
}
).ToList();
var selectItems = new List<MyHelpers.MySelectItem>(meetingsQuery.Count);
foreach (var record in meetingsQuery)
{
var item = new MyHelpers.MySelectItem
{
Text = record.DisplayValue,
Value = record.Value
};
if (record.Expired)
{
item.Class = "disabled";
item.Disabled = "disabled";
}
selectItems.Add(item);
}
ViewBag.MeetingData = selectItems;
}
Here are sample data for models:
Applicant:
ApplicantID : 100
SubmitDate : 01/11/2013
Name : Christof
Surname : Jahnsen
MeetingId : 1
Meeting:
MeetingID : 1
MeetingName : City Information Days
MeetingStartDate : 01/01/2014
MeetingEndDate : 02/01/2014
TotalParticipant : 2 (for example)
MeetingCityId : 500
ParticipantCityAId : 501
ParticipantCityBId : 502
City:
CityID : 500 / 501 / 502
CityName : London / Paris / NY
Update -----------------------------------------------------------------------
Razor:
#Html.LabelFor(m => m.Applicant.MeetingId)
#Html.MyDropdownListFor(m => m.Applicant.MeetingId, ViewBag.MeetingData as List<MyHelpers.MySelectItem>, "---- Select ----",
new { name = "meetingId", id = "meetingId" })
#Html.ValidationMessageFor(m => m.Applicant.MeetingId, null, new { #class = "ValidationErrors" })
Controller:
public ViewResult Add()
{
PopulateDropDownList();
ApplicantViewModel model = new ApplicantViewModel
{
Applicant = new Applicant(),
Applicants = repository.Applicants,
Lookups = repository.Lookups,
Cities = repository.Cities
.ToList()
};
return View(model);
}
[HttpPost]
public ActionResult Add(ApplicantViewModel model)
{
ApplicantViewModel viewModel;
if (ModelState.IsValid)
{
model.Applicant.SubmitDate = DateTime.Now;
repository.SaveApplicant(model.Applicant);
PopulateDropDownList(model.Applicant);
return View("Completed", ViewBag.ApplicantId = model.Applicant.ApplicantID);
}
else
{
// there is something wrong with the data values
PopulateDropDownList();
TempData["message"] = "Please try again.";
viewModel = new ApplicantViewModel
{
Applicant = new Applicant(),
Applicants = repository.Applicants,
Lookups = repository.Lookups,
Cities = repository.Cities
.ToList()
};
return View(viewModel);
}
}
You need grouping, so use something like this
var meetingsQuery = from meeting in repository.Meetings
join cityA in repository.Cities on meeting.MeetingCityId equals cityA.CityID into CitiesA
join cityB in repository.Cities on meeting.ParticipantCityAId equals cityB.CityID into CitiesB
join cityC in repository.Cities on meeting.ParticipantCityBId equals cityC.CityID into citiesC
from cityA in citiesA.DefaultIfEmpty()
from cityB in citiesB.DefaultIfEmpty()
from cityC in citiesC.DefaultIfEmpty()
orderby cityA.CityID
select new
{
CityID = cityA.CityID,
CityName = cityA.CityName,
MeetingDate = meeting.MeetingStartDate,
MeetingName = meeting.MeetingName,
NameofMeetingCityIdA = cityA != null ? cityA.CityName : null,
NameofMeetingCityIdB = cityB != null ? cityB.CityName : null,
NameofMeetingCityIdC = cityC != null ? cityC.CityName : null
}
var meetings = from meeting in meetingsQuery.AsEnumerable()
group meeting by new {
meeting.CityID,
meeting.MeetingDate,
meeting.NameofMeetingCityIdA
} into grouppedMeeting
select new {
Value = grouppedMeeting.Key.CityID.ToString(),
DisplayValue = string.Format("{0} ({1:dd MMMM yyyy})", grouppedMeeting.Key.NameofMeetingCityIdA, grouppedMeeting.Key.MeetingDate),
Expired = grouppedMeeting.Key.MeetingDate < DateTime.UtcNow,
TotalMeetingById= grouppedMeeting.Count()
}
UPDATE
in this code
// there is something wrong with the data values
PopulateDropDownList();
TempData["message"] = "Please try again.";
viewModel = new ApplicantViewModel
{
Applicant = new Applicant(),
Applicants = repository.Applicants,
Lookups = repository.Lookups,
Cities = repository.Cities
.ToList()
};
return View(viewModel);
you don't mark any item as selected, you only add items to viewbag
Finally I solved the problem with the help of using an external method out of Lambda expression.
private void PopulateMeetingsDropDownList(object selectedMeetings = null)
{
var meetingsQuery = repository.Meetings
.GroupJoin(repository.Cities, m => m.MeetingCityId, c => c.CityID, (m, c) => new { m, cA = c.DefaultIfEmpty() })
.SelectMany(z => z.cA.Select(cA => new { m = z.m, cA }))
.GroupJoin(repository.Cities, m => m.m.ParticipantCityAId, c => c.CityID, (m, c) => new { m.m, m.cA, cB = c.DefaultIfEmpty() })
.SelectMany(w => w.cB.Select(cB => new { m = w.m, cA = w.cA, cB }))
.GroupJoin(repository.Cities, m => m.m.ParticipantCityBId, c => c.CityID, (m, c) => new { m.m, m.cA, m.cB, cC = c.DefaultIfEmpty() })
.SelectMany(t => t.cC.Select(cC => new { m = t.m, cA = t.cA, cB = t.cB, cC }))
.Select(
m =>
new
{
TotalParticipant = m.m.TotalParticipant,
MeetingID = m.m.MeetingID,
CityID = m.cA.CityID,
CityName = m.cA.CityName,
MeetingDate = m.m.MeetingStartDate,
MeetingName = m.m.MeetingName,
NameofMeetingCityIdA = m.cA != null ? m.cA.CityName : null,
NameofMeetingCityIdB = m.cB != null ? m.cB.CityName : null,
NameofMeetingCityIdC = m.cC != null ? m.cC.CityName : null
})
.OrderBy(x => x.CityName)
.AsEnumerable()
.Select(
i => new
{
Value = i.MeetingID.ToString(),
DisplayValue = string.Format("{0} ({1:dd MMMM yyyy})", i.NameofMeetingCityIdA, i.MeetingDate)),
Expired = i.MeetingDate < DateTime.UtcNow,
MaksimumCount = i.TotalParticipant,
CurrentCount = GetMeetingCount(i.MeetingID)
}
).ToList();
var selectItems = new List<MyHelpers.MySelectItem>(meetingsQuery.Count);
foreach (var record in meetingsQuery)
{
var item = new MyHelpers.MySelectItem
{
Text = record.DisplayValue,
Value = record.Value
};
//If Meeting Date is expired or Count for the current record >= Total Participant
if (record.Expired || record.CurrentCount >= record.MaksimumCount)
{
item.Class = "disabled";
item.Disabled = "disabled";
}
selectItems.Add(item);
}
ViewBag.MeetingData = selectItems;
}
public int GetMeetingCount(int meetingId)
{
return repository.Applicants.Count(x => x.MeetingId == meetingId);
}
The first running of the code I encountered "There is already an open DataReader associated with this Command which must be closed first." error. But adding "MultipleActiveResultSets=True;" parameter to teh ConnectionString solved this problem and now it works properly.
Unit testing of the role provider to fail.
[TestMethod]
public void FindUsersInRole()
{
Mock<IUsersInRoleRepository> userInRoleMock = new Mock<IUsersInRoleRepository>();
userInRoleMock.Setup(m => m.UsersInRoles).Returns(new UsersInRole[] {
new UsersInRole { UserId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"), RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") },
new UsersInRole { UserId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"), RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") },
new UsersInRole { UserId = Guid.Parse("cccccccc-cccc-cccc-cccc-cccccccccccc"), RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") },
new UsersInRole { UserId = Guid.Parse("dddddddd-dddd-dddd-dddd-dddddddddddd"), RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") },
new UsersInRole { UserId = Guid.Parse("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"), RoleId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb") }
}.AsQueryable());
Mock<IRoleRepository> roleMock = new Mock<IRoleRepository>();
roleMock.Setup(m => m.Roles).Returns(new Role[] {
new Role { RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"), RoleName = "test" },
new Role { RoleId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"), RoleName = "admin" }
}.AsQueryable());
Mock<IUserRepository> userMock = new Mock<IUserRepository>();
userMock.Setup(m => m.Users).Returns(new User[] {
new User { UserId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"), UserAccount = "abcdef" },
new User { UserId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"), UserAccount = "bcdef" },
new User { UserId = Guid.Parse("cccccccc-cccc-cccc-cccc-cccccccccccc"), UserAccount = "cdef" },
new User { UserId = Guid.Parse("dddddddd-dddd-dddd-dddd-dddddddddddd"), UserAccount = "bcdf" },
new User { UserId = Guid.Parse("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"), UserAccount = "abcde" }
}.AsQueryable());
RoleProvider target = new RoleProvider(userMock.Object, roleMock.Object, userInRoleMock.Object);
string[] result = target.FindUsersInRole("test", "cde");
Assert.AreEqual(result[0], "abcdef");
Assert.AreEqual(result[1], "bcdef");
Assert.AreEqual(result[2], "cdef");
}
Unit Test Code
string[] result = target.FindUsersInRole("test", "cde"); <-- error
FindUsersInRole - Gets an array of user names in a role where the user name contains the specified user name to match.
System.NullReferenceException is raised and try to debug.
Why NullReferenceException?
PS - FindUsersInRole (RoleProvider)
public override string[] FindUsersInRole(string roleName, string userAccountToMatch)
{
Guid roleId = roleRepository.GetRole(roleName).RoleId; // RoleId Retrun.. NullReferenceException
var roleInUsers = (from ru in usersInRoleRepository.UsersInRoles
where ru.RoleId == roleId
select ru.UserId).ToArray();
var findUserResult = (from u in userRepository.Users
where roleInUsers.Contains(u.UserId) && u.UserAccount.Contains(userAccountToMatch)
select u.UserAccount).ToArray();
return findUserResult;
}
Your cde is not a fake user in a mackUserAccount . So its return null.
try this below code string[] result = target.FindUsersInRole("test", "abcdef"); instead of
string[] result = target.FindUsersInRole("test", "cde");