TableName.RowName retrieves Nothing in MVC - asp.net-mvc

I have a model class called "KelimeTuru" designed as shown below:
public partial class KelimeTuru
{
public int Id { get; set; }
public int KelimeId { get; set; }
public int MenseiId { get; set; }
public int TurId { get; set; }
public int AnlamTurleriId { get; set; }
public int SozlukTuruId { get; set; }
public Nullable<int> SesId { get; set; }
public Nullable<int> VideoId { get; set; }
public Nullable<int> ResimId { get; set; }
public Nullable<int> SembolId { get; set; }
public Nullable<int> BirimId { get; set; }
public Nullable<int> SimgeId { get; set; }
public string Anlam { get; set; }
public string Transkript { get; set; }
public virtual AnlamTurleri AnlamTurleri { get; set; }
public virtual Birim Birim { get; set; }
public virtual Kelime Kelime { get; set; }
public virtual Mensei Mensei { get; set; }
public virtual Sembol Sembol { get; set; }
public virtual Ses Ses { get; set; }
public virtual Simge Simge { get; set; }
public virtual SozlukTuru SozlukTuru { get; set; }
public virtual Turler Turler { get; set; }
public virtual Video Video { get; set; }
public virtual Resim Resim { get; set; }
}
And It retrieves the required data if we use the Id of the record properly like this:
public ActionResult Details(int id=0)
{
SozlukEntities db = new SozlukEntities();
KelimeTuru kelime = db.KelimeTuru.Find(id);
if (kelime == null)
{
return HttpNotFound();
}
return View(kelime);
}
I want to retrieve records according to their "KelimeId"s not "Id"s so replaced the word "id" with "KelimeId" in my code. But got a "404.0 - Not Found" error.
Could you please help me retrieve "KelimeTuru" table using KelimeId?

try this:
KelimeTuru kelime = db.KelimeTuru.SingleOrDefault(x => x.KelimeId == id);
Find method works only on Primary Key Property, means if your property is decorated with [Key] attribute, then Find() will be able to find record, otherwise it wil not fetch the record.

It sounds like you want something like this:
KelimeTuru kelime = db.KelimeTuru.Where(x => x.KelimeId == id).SingleOrDefault();

Related

how to select from client model all clients thats make an order orderby Count of purchase

I want to select from client model all client without duplicate client and order them by count of the purchases they already did
This is model of client :
public class Client
{
public int ID { get; set; }
public string FacebookName { get; set; }
public string RealName { get; set; }
public string Mobile { get; set; }
public int RegionID { get; set; }
public string Addressdetails { get; set; }
public string Email { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfStart { get; set; }
public virtual Region Region { get; set; }
public virtual List<Order> order { get; set; }
}
this is Order model :
public class Order
{
public int ID { get; set; }
public int ClientID { get; set; }
public Nullable<int> ShippingID { get; set; }
public Nullable<int> SharepointID { get; set; }
public Nullable<int> CallStatuID { get; set; }
public Nullable<int> ShippingStatuID { get; set; }
public Nullable<int> ShippingStatuReasonsID { get; set; }
[DataType(DataType.Date)]
public DateTime Date { get; set; }
// public int OrderStatusID { get; set; }
public Nullable<decimal> ShippingCost { get; set; }
public string purchasetype { get; set; }
public string Notes { get; set; }
public Nullable<decimal> Discount { get; set; }
public decimal Total { get; set; }
[DefaultValue(false)]
public bool Prepared { get; set; }
[DefaultValue(false)]
public bool Done { get; set; }
[DefaultValue(false)]
public bool Shipe { get; set; }
[DefaultValue(false)]
public bool Collected { get; set; }
[DataType(DataType.Date)]
public Nullable<DateTime> DateOfCall { get; set; }
[DataType(DataType.Date)]
public Nullable<DateTime> StockCheckDate { get; set; }
[DataType(DataType.Date)]
public Nullable<DateTime> ShippingDate { get; set; }
public virtual List<OrderDetail> orderdetails { get; set; }
public virtual Client Client { get; set; }
public virtual Shipping shipping { get; set; }
public virtual Sharepoint sharepoint { get; set; }
public virtual CallStatu callStatu { get; set; }
public virtual ShippingStatu ShippingStatus { get; set; }
public virtual ShippingStatuReason ShippingStatuReasons { get; set; }
}
and finally this is OrderDetails model:
public class OrderDetail
{
public int ID { get; set; }
public int OrderID { get; set; }
public Nullable<int> ItemID { get; set; }
public Nullable<int> SizeID { get; set; }
public int ColorID { get; set; }
public decimal Price { get; set; }
public Nullable<int> StockStatuID { get; set; }
public Nullable<int> StockStatuReasonsID { get; set; }
public int Quantity { get; set; }
public decimal Total { get; set; }
public virtual Order order { get; set; }
public virtual Item item { get; set; }
public virtual Size size { get; set; }
public virtual Colors Colors { get; set; }
public virtual StockStatu stockStatus { get; set; }
public virtual StockStatuReason StockStatuReasons { get; set; }
}
I tried this way but it the select is repeat Clients If they make more than one purchase:
public JsonResult TopClientCount()
{
var index = (from dex in db.Clients
join O in db.Orders on dex.ID equals O.ClientID
select new
{
RealName = dex.RealName,
FacebookName = dex.FacebookName,
GovernorateName = dex.Region.governorate.GovernorateName,
RegionName = dex.Region.RegionName,
OrderCount = O.orderdetails.Count()
}).AsEnumerable().OrderByDescending(o => o.OrderCount)
.Distinct()
.ToList();
return Json(index, JsonRequestBehavior.AllowGet);
}
You can use let statement and you can use navigation properties i.e (order ,orderdetails) instead of joins
var index = (from dex in db.Clients
//This will give you all the order details for a client
let orderDetails = dex.order.SelectMany(p=> p.orderdetails)
select new
{
RealName = dex.RealName,
FacebookName = dex.FacebookName,
GovernorateName = dex.Region.governorate.GovernorateName,
RegionName = dex.Region.RegionName,
OrderCount = orderDetails.Count()
}).AsEnumerable().OrderByDescending(o => o.OrderCount)
.Distinct()
.ToList();

Eager loading with include method does not return data from collection

I wanted to eager load a collection but it does not returns any data
I have tried nothing
//here is my controller
var accountGroup = await db.AccountGroups.Include(a=>a.AccountGroupTypes)
.Include(a=>a.AccountPrimaryGroups).ToListAsync();
//here is my model
public int? Id { get; set; }
public string Name { get; set; }
public int AccountGroupTypeId { get; set; }
public ICollection<AccountGroupType> AccountGroupTypes { get; set; }
public int AccountPrimaryGroupId { get; set; }
public ICollection<AccountPrimaryGroup> AccountPrimaryGroups { get; set; }
public DateTime CreationDateUtcNow{ get; set; }
It returns AccountGroupData but It does not return AccountGroupTypes and AccountPrimaryGroup data
Mark your AccountGroupTypes and AccountPrimaryGroups as virtual properties and be sure that you have a parameterless constructor which is initializing those properties.
public int? Id { get; set; }
public string Name { get; set; }
public int AccountGroupTypeId { get; set; }
public vitual ICollection<AccountGroupType> AccountGroupTypes { get; set; }
public int AccountPrimaryGroupId { get; set; }
public virtual ICollection<AccountPrimaryGroup> AccountPrimaryGroups { get; set; }
public DateTime CreationDateUtcNow{ get; set; }
public AccountGroup()
{
this.AccountGroupTypes = new HashSet<AccountGroupType>();
this.AccountPrimaryGroups = new HashSet<AccountPrimaryGroups>();
}

Automapper with nested entity not working

I have two classes which are mentioned below. I am trying to map those through Auto Mapper but it is not working.
public class VMTemplates
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
public System.DateTime TimeStamp { get; set; }
public virtual ICollection<VMTemplateGroup> VMTemplateGroup { get; set; }
}
public VMTemplateViewModel()
{
VMTemplateGroup = new List<VMTemplateGroupViewModel>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
[Required(ErrorMessage = "Please Upload File")]
[Display(Name = "Upload File")]
[ValidateFile]
public HttpPostedFileBase TemplateUpload { get; set; }
public System.DateTime TimeStamp { get; set; }
public List<VMTemplateGroupViewModel> VMTemplateGroup { get; set; }
I am using this code to map them
confi.CreateMap<VMTemplateViewModel, VMTemplates>().ReverseMap();
confi.CreateMap<VMTemplateGroupViewModel, VMTemplateGroup>().ReverseMap();
calling code
public VMTemplates GetVMTemplateById(int id)
{
return DataContext.VMTemplates.Include("VMTemplateGroup").Where(a => a.Id == id).FirstOrDefault();
}
This is where exception happens. I get stack overflow exception
public VMTemplateViewModel GetVMTemplateById(int templateId)
{
var result = _vmTemplateRepository.GetVMTemplateById(templateId);
return _autoMapperService.MapEntity<VMTemplateViewModel>(result);
}

Code First Many to Many Mess what is going on here?

Here is a sniplet of my model:
public class ContractParent
{
public int ContractParentID { get; set; }
public string Name { get; set; }
public string Verbiage { get; set; }
public int Position { get; set; }
public bool IncludedByDefault { get; set; }
public virtual IEnumerable<ContractChild> ContractChilds { get; set; }
public virtual bool HasOnlyOneChild { get; set; }
}
public class ContractParentItem
{
public int ContractParentItemID { get; set; }
public virtual int ContractParentID { get; set; }
public virtual ContractParent ContractParent { get; set; }
public int ChargeID { get; set; }
public virtual Charge Charge { get; set; }
}
public class Charge
{
public int ChargeID { get; set; }
public virtual ChargeType ChargeType { get; set; }
public int ChargeTypeID { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<ChargeContract> ChargeContracts { get; set; }
public virtual Company Company { get; set; }
public virtual int? CompanyID { get; set; }
public virtual IEnumerable<ContractParentItem> ContractParentItems { get; set; }
public virtual IEnumerable<ContractChildItem> ContractChildItems { get; set; }
}
When i try to access a Charge with ChargeID = 687:
Charge.ContractParentItem is null.
But its not!
Looking at my table ContractParentItem in SQL
There is an entity:
ContractParentItemID=1
ContractParentID=8
ChargeID=687
I know i am missing something here.
public class Proposals : DbContext
{
public DbSet<Charge> Charges { get; set; }
public DbSet<ContractParent> ContractParents { get; set; }
public DbSet<ContractParentItem> ContractParentItems { get; set; }
}
Instead of
public virtual IEnumerable<ContractParentItem> ContractParentItems { get; set; }
you should have
public virtual ICollection<ContractParentItem> ContractParentItems { get; set; }

A required field that exists in the view will always make model.state false

I have the following model class:-
public class TMSServer_Validation
{
[Required]
public string ILOIP { get; set; }
}
and the following view :-
#model TMS.ViewModels.ServerJoin
<div >
<span class="f"> ILOIP</span>
#Html.EditorFor(model =>model.Server.ILOIP)
#Html.ValidationMessageFor(model =>model.Server.ILOIP)
</div>
and the following post action method:-
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ServerJoin sj, FormCollection formValues)
{
//code goes here..
repository.InsertOrUpdateServer(sj.Server, User.Identity.Name, sj.Resource.RESOURCEID);
repository.Save();
return RedirectToAction("Index");
and the following view model class:-
public class ServerJoin
{
public TMSServer Server { get; set; }
public Resource Resource { get; set; }
public Technology Technology { get; set; }
public ComponentDefinition ComponentDefinition { get; set; }
}
but whenever i want to edit an object the model state will be False, and the error message indicates that the ILOP field is required, although there is a value for it on the view?
So what is causing this problem ?
UPDATE
Th model class is :-
[MetadataType(typeof(TMSServer_Validation))]
public partial class TMSServer
{
public TMSServer()
{
this.TMSServers1 = new HashSet<TMSServer>();
this.TMSVirtualMachines = new HashSet<TMSVirtualMachine>();
}
public int ServerID { get; set; }
public Nullable<int> ServerModelID { get; set; }
public int DataCenterID { get; set; }
public string ILOIP { get; set; }
public int RackID { get; set; }
public Nullable<int> StatusID { get; set; }
public Nullable<int> BackUpStatusID { get; set; }
public int RoleID { get; set; }
public Nullable<int> OperatingSystemID { get; set; }
public Nullable<int> VirtualCenterID { get; set; }
public string Comment { get; set; }
public byte[] timestamp { get; set; }
public long IT360SiteID { get; set; }
public virtual DataCenter DataCenter { get; set; }
public virtual OperatingSystem OperatingSystem { get; set; }
public virtual ServerModel ServerModel { get; set; }
public virtual Technology Technology { get; set; }
public virtual TechnologyBackUpStatu TechnologyBackUpStatu { get; set; }
public virtual TechnologyRole TechnologyRole { get; set; }
public virtual TechnologyStatu TechnologyStatu { get; set; }
public virtual TMSRack TMSRack { get; set; }
public virtual ICollection<TMSServer> TMSServers1 { get; set; }
public virtual TMSServer TMSServer1 { get; set; }
public virtual ICollection<TMSVirtualMachine> TMSVirtualMachines { get; set; }
}

Resources