DevExpress PopupControl inside GridView modal edit form - asp.net-mvc

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();
}

Related

How to get all action , controller and area names while running asp core 3.1

i have an asp.net core 3.1 application and i want to get all controller , action and area names when my application is running like get action names with reflection in mvc.
Is there any way ?
Try this:
1.Model:
public class ControllerActions
{
public string Controller { get; set; }
public string Action { get; set; }
public string Area { get; set; }
}
2.Display the Controller,Action and Area Name:
[HttpGet]
public List<ControllerActions> Index()
{
Assembly asm = Assembly.GetExecutingAssembly();
var controlleractionlist = asm.GetTypes()
.Where(type => typeof(Controller).IsAssignableFrom(type))
.SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
.Select(x => new
{
Controller = x.DeclaringType.Name,
Action = x.Name,
Area = x.DeclaringType.CustomAttributes.Where(c => c.AttributeType == typeof(AreaAttribute))
}).ToList();
var list = new List<ControllerActions>();
foreach (var item in controlleractionlist)
{
if (item.Area.Count() != 0)
{
list.Add(new ControllerActions()
{
Controller = item.Controller,
Action = item.Action,
Area = item.Area.Select(v => v.ConstructorArguments[0].Value.ToString()).FirstOrDefault()
});
}
else
{
list.Add(new ControllerActions()
{
Controller = item.Controller,
Action = item.Action,
Area = null,
});
}
}
return list;
}
In my application I didn't require finding areas, so I ended up creating a simplified version based on the accepted answer. If it's useful to anyone else, here it is:
public static class ControllerActionEnumerator
{
public static List<ControllerAndItsActions> GetAllControllersAndTheirActions()
{
Assembly asm = Assembly.GetExecutingAssembly();
IEnumerable<Type> controllers = asm.GetTypes().Where(type => type.Name.EndsWith("Controller"));
var theList = new List<ControllerAndItsActions>();
foreach (Type curController in controllers)
{
List<string> actions = curController.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public)
.Where(m => m.CustomAttributes.Any(a => typeof(HttpMethodAttribute).IsAssignableFrom(a.AttributeType)))
.Select(x => x.Name)
.ToList();
theList.Add(new ControllerAndItsActions(curController.Name, actions));
}
return theList;
}
}
public class ControllerAndItsActions
{
public string Controller { get; }
public List<string> Actions { get; }
public ControllerAndItsActions(string controller, List<string> actions) => (Controller, Actions) = (controller, actions);
}
Try this:
ControllerFeature controllerFeature = new ControllerFeature();
this.ApplicationPartManager.PopulateFeature(controllerFeature);
IEnumerable<TypeInfo> typeInfos = controllerFeature.Controllers;
ApplicationPartManager must use DI to your class.
I wrote new code with a Controller and Action DisplayNames.
Assembly assembly = Assembly.GetExecutingAssembly();
var controllersList = assembly.GetTypes().Where(ctype => typeof(Controller).IsAssignableFrom(ctype)).Select(type => new { ty = type, methods = type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public).Where(y => Attribute.IsDefined(y, typeof(LogRequestAttribute))) }).Where(type => type.methods.Any(x => Attribute.IsDefined(x, typeof(LogRequestAttribute)))).Select(controller => new
{
AreaName = (controller.ty.GetCustomAttribute(typeof(AreaAttribute)) as AreaAttribute)?.RouteValue,
ControllerTitle = (controller.ty.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute)?.DisplayName,
ControllerName = controller.ty.Name,
Actions = controller.methods.Select(action => new
{
ActionTitle = (action.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute)?.DisplayName,
ActionName = action.Name,
}).ToList(),
}).ToList();
// group by on area
var areaList = controllersList.GroupBy(group => group.AreaName).Select(ar => new
{
AreaName = ar.Key,
Controllers = ar.Select(co => new
{
ControllerTitle = co.ControllerTitle,
ControllerName = co.ControllerName,
Actions = co.Actions,
}).ToList(),
}).ToList();

remote attribute does not allow to post

I'm trying to check if TerminalID already is taken by another model. The Ajax is posting back correctly and error message also can be seen, but the page will not allow me to submit , I only need to check this information while input to display error message and then post anyway . help me please
Model :
public class MoveModel
{
[Required]
[Remote("CheckExistTrm", "MoveModel")]
public int TerminalID { get; set; }
public string User { get; set; }
........
}
Controller:
public JsonResult CheckExistTrm(int TerminalID)
{
var terminal = db.Terminals.Find(TerminalID);
if (terminal == null)
return null;
var agrdet = (from t in db.AgreementDetails where (t.TerminalID == terminal.TerminalID && t.Condition == "New") select t).FirstOrDefault();
if (agrdet != null)
{
var agreement = db.Agreements.Find(agrdet.AgreementID);
return Json("consider! this terminal is active in the agreement: " + agreement.AgreementNumber ,JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
View (I am using devexpress ):
#using (Html.BeginForm("CreateAndEdit", "MoveModel", FormMethod.Post, new { #class = "edit_form" })){
#Html.AntiForgeryToken()
#Html.Hidden("MoveModelID")
<div class="line">
#Html.DevExpress().Label(
settings =>
{
settings.ControlStyle.CssClass = "label";
settings.AssociatedControlName = "TerminalID";
settings.Text = "ტემრინალი";
}
).GetHtml()
#Html.DevExpress().ComboBox(
settings =>
{
settings.Name = "TerminalID";
settings.ControlStyle.CssClass = "editor";
settings.Properties.TextField = "Name";
settings.Properties.ValueField = "TerminalID";
settings.Properties.ValueType = typeof(int);
settings.Properties.DropDownStyle = DropDownStyle.DropDown;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
}
).BindList(LeaseReg.Models.Terminal.getTerminals()).Bind(Model.TerminalID).GetHtml()
#Html.ValidationMessageFor(model => model.TerminalID,null, new { #class = "validator" })
</div>
<div class="line">
#Html.DevExpress().Label(
settings =>
{
settings.ControlStyle.CssClass = "label";
}
).GetHtml()
#Html.DevExpress().Button(
settings =>
{
settings.Name = "btnUpdate";
settings.ControlStyle.CssClass = "button";
settings.Text = "დადასტურება";
settings.UseSubmitBehavior = true;
}
).GetHtml()
#Html.DevExpress().Button(
settings =>
{
settings.Name = "btnCancel";
settings.ControlStyle.CssClass = "button"; ;
settings.Text = "გაუქმება";
settings.ClientSideEvents.Click = "function(s, e){ document.location='" + DevExpressHelper.GetUrl(new { Controller = "MoveModel", Action = "Index" }) + "'; }";
}
).GetHtml()
</div>
#Html.ValidationSummary(true);}

Json Data from datatable

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

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'Int32' for method 'Edit(Int32)'

I am performing CRUD operation using linq to sql. But while clicking on Edit, Details or delete it gives me error i.e. "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'CRUD_using_LinQ_to_SQL_in_MVC.Controllers.OTDController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
I checked the solution and found that, while running application url didn't get ID parameter. But i dont understand what should i change in my code.. Can you please help me...
My Controller Code:
using System;
namespace CRUD_using_LinQ_to_SQL_in_MVC.Controllers
{
public class OTDController : Controller
{
private IOTddataRepository repository;
public OTDController()
: this(new OtdDataRepository())
{
}
public OTDController(IOTddataRepository _repository)
{
repository = _repository;
}
//-----------------------Index--------------------------
public ActionResult Index()
{
var otddata = repository.Getallotddata();
return View(otddata);
}
//-----------------------Details--------------------------
public ActionResult Details(int id)
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
//-----------------------Create--------------------------
public ActionResult Create()
{
return View(new OtdModelClass());
}
[HttpPost]
public ActionResult Create(OtdModelClass otdmodel)
{
try
{
if (ModelState.IsValid)
{
repository.Insertotddata(otdmodel);
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Problem in Data Saving");
}
return View(otdmodel);
}
//-----------------------EDIT--------------------------
public ActionResult Edit(int id)
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
[HttpPost]
public ActionResult Edit(OtdModelClass otdclass)
{
try
{
if (ModelState.IsValid)
{
repository.Updateotddata(otdclass);
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Problem in editing and Updating data");
}
return View(otdclass);
}
//-----------------------Delete--------------------------
public ActionResult Delete(int id, bool? savechangeserror)
{
if (savechangeserror.GetValueOrDefault())
{
ViewBag.ErrorMessage = "Problem in Deleting";
}
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
try
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
repository.Deleteotddata(id);
}
catch (DataException)
{
return RedirectToAction("Delete", new System.Web.Routing.RouteValueDictionary {
{"id",id},
{"SaveChangesError",true}});
}
return RedirectToAction("Index");
}
}
}
My OTD class Code:
public class OtdDataRepository : IOTddataRepository
{
private MVCLoginMasterLogDataClassesDataContext otdcontextobj;
public OtdDataRepository()
{
otdcontextobj = new MVCLoginMasterLogDataClassesDataContext();
}
public IEnumerable<OtdModelClass> Getallotddata()
{
IList<OtdModelClass> otddatalist = new List<OtdModelClass>();
var myselectallquery = from otduser in otdcontextobj.tbl_MVC_Login_Master_Logs select otduser;
var otd = myselectallquery.ToList();
foreach (var otddata in otd)
{
otddatalist.Add(new OtdModelClass()
{
Srno=Convert.ToInt32(otddata.Srno),
MemberCode = otddata.MemberCode,
LoginID = otddata.LoginID,
OTDPassword = otddata.OTDPassword,
BBSID = otddata.BBSID,
IPAddress = otddata.IPAddress,
ServerType = otddata.ServerType,
OTDStatus = otddata.OTDStatus,
RemoteIP = otddata.RemoteIP,
RemotePort = otddata.RemotePort,
AllowDownload = otddata.AllowDownload,
OTDTimeStamp = otddata.OTDTimeStamp,
MemberType = otddata.MemberType,
EQ = otddata.EQ,
EQD = otddata.EQD,
BFX = otddata.BFX,
SLB = otddata.SLB,
Others = otddata.Others
});
}
return otddatalist;
}
public OtdModelClass Getotddatabysrno(int id)
{
var getotddataquery = from otduser in otdcontextobj.tbl_MVC_Login_Master_Logs
where otduser.Srno == id
select otduser;
var otddata = getotddataquery.FirstOrDefault();
var otdmodel = new OtdModelClass()
{
Srno = Convert.ToInt32(otddata.Srno),
MemberCode = otddata.MemberCode,
LoginID = otddata.LoginID,
OTDPassword = otddata.OTDPassword,
BBSID = otddata.BBSID,
IPAddress = otddata.IPAddress,
ServerType = otddata.ServerType,
OTDStatus = otddata.OTDStatus,
RemoteIP = otddata.RemoteIP,
RemotePort = otddata.RemotePort,
AllowDownload = otddata.AllowDownload,
OTDTimeStamp = otddata.OTDTimeStamp,
MemberType = otddata.MemberType,
EQ = otddata.EQ,
EQD = otddata.EQD,
BFX = otddata.BFX,
SLB = otddata.SLB,
Others = otddata.Others
};
return otdmodel;
}
public void Insertotddata(OtdModelClass otdmodel_obj)
{
var empdata = new tbl_MVC_Login_Master_Log()
{
Srno = Convert.ToInt32(otdmodel_obj.Srno),
MemberCode = otdmodel_obj.MemberCode,
LoginID = otdmodel_obj.LoginID,
OTDPassword = otdmodel_obj.OTDPassword,
BBSID = otdmodel_obj.BBSID,
IPAddress = otdmodel_obj.IPAddress,
ServerType = otdmodel_obj.ServerType,
OTDStatus = otdmodel_obj.OTDStatus,
RemoteIP = otdmodel_obj.RemoteIP,
RemotePort = otdmodel_obj.RemotePort,
AllowDownload = otdmodel_obj.AllowDownload,
OTDTimeStamp = otdmodel_obj.OTDTimeStamp,
MemberType = otdmodel_obj.MemberType,
EQ = otdmodel_obj.EQ,
EQD = otdmodel_obj.EQD,
BFX = otdmodel_obj.BFX,
SLB = otdmodel_obj.SLB,
Others = otdmodel_obj.Others
};
otdcontextobj.tbl_MVC_Login_Master_Logs.InsertOnSubmit(empdata);
otdcontextobj.SubmitChanges();
}
public void Deleteotddata(int id)
{
tbl_MVC_Login_Master_Log otd_deletelog = otdcontextobj.tbl_MVC_Login_Master_Logs.Where(otduser => otduser.Srno == id).SingleOrDefault();
otdcontextobj.tbl_MVC_Login_Master_Logs.DeleteOnSubmit(otd_deletelog);
otdcontextobj.SubmitChanges();
}
public void Updateotddata(OtdModelClass otdmodel_obj)
{
tbl_MVC_Login_Master_Log otd_updatelog = otdcontextobj.tbl_MVC_Login_Master_Logs.Where(otduser=>otduser.Srno==otdmodel_obj.Srno).SingleOrDefault();
otd_updatelog.Srno = otdmodel_obj.Srno;
otd_updatelog.MemberCode = otdmodel_obj.MemberCode;
otd_updatelog.LoginID = otdmodel_obj.LoginID;
otd_updatelog.OTDPassword = otdmodel_obj.OTDPassword;
otd_updatelog.BBSID = otdmodel_obj.BBSID;
otd_updatelog.IPAddress = otdmodel_obj.IPAddress;
otd_updatelog.ServerType = otdmodel_obj.ServerType;
otd_updatelog.OTDStatus = otdmodel_obj.OTDStatus;
otd_updatelog.RemoteIP = otdmodel_obj.RemoteIP;
otd_updatelog.RemotePort = otdmodel_obj.RemotePort;
otd_updatelog.AllowDownload = otdmodel_obj.AllowDownload;
otd_updatelog.OTDTimeStamp = otdmodel_obj.OTDTimeStamp;
otd_updatelog.MemberType = otdmodel_obj.MemberType;
otd_updatelog.EQ = otdmodel_obj.EQ;
otd_updatelog.EQD = otdmodel_obj.EQD;
otd_updatelog.BFX = otdmodel_obj.BFX;
otd_updatelog.SLB = otdmodel_obj.SLB;
otd_updatelog.Others = otdmodel_obj.Others;
otdcontextobj.SubmitChanges();
}
}
Can you please help me...
The framework is telling you that the link you are clicking on to call the Edit and Delete action methods is not providing an int parameter named id which the action method is expecting to find somewhere in the submitted data. This is usually provided either in the URL, query string or submitted variables.
If that is not enough for you to spot the problem, post your view code specially the section related to the links.

How to create foreign key relationship in Entity Framework CodeFirst

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;}
}

Resources