I have a method where (artist and genre) throws null reference exception, when i use select clause. if i don't use select clause then it can't convert system.collections.generic.list to system.collections.generic.ienumerable.
public ActionResult Attending()
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
var gigs = _context.Attendances.Include(a => a.Gig.Artist).Include(a => a.Gig.Genre).Where(a => a.AttendeeId == userId).ToList();
var viewModel = new GigsViewModel()
{
UpcomingGigs = gigs,
ShowActions = User.Identity.IsAuthenticated,
Heading = "Gigs I'm Attending"
};
return View("Gigs", viewModel);
}
Here is my ViewModel:
public class GigsViewModel
{
public IEnumerable<Gig> UpcomingGigs { get; set; }
public bool ShowActions { get; set; }
public string Heading { get; set; }
}
Here is my Attendance class
public class Attendance
{
public Gig Gig { get; set; }
public ApplicationUser Attendee { get; set; }
[Key]
public int GigId { get; set; }
[Key]
public string AttendeeId { get; set; }
}
Related
When I want to call a property of my object property Trip from TripApplicationUser model class its values are null. So I do not know how to initialize the Trip object to get its property values later on and to now have problem with indexing in database. I have pasted here the most important parts of code.
[Authorize]
public async Task<ActionResult> Enroll(int id)
{
if (id == null)
{
return NotFound();
}
var currentTrip = await _context.Trip.FindAsync(id);
var currentUser = await _userManager.GetUserAsync(User);
var isAlreadyEnrolled = _context.TripApplicationUsers.Where(tu => tu.ApplicationUserId.Equals(currentUser.Id) && tu.TripId == id);
var UserTrips = isAlreadyEnrolled.ToList();
if (currentTrip.TripSeats > 0 && !UserTrips.Any())
{
ViewBag.process = "done";
currentTrip.TripSeats--;
_context.Update(currentTrip);
var rowToSave = new TripApplicationUser
{
TripId = currentTrip.TripId,
ApplicationUserId = currentUser.Id,
Trip = currentTrip //HOW SHOULD I INITIALIZE IT ACTUALLY?
};
_context.Add(rowToSave);
await _context.SaveChangesAsync();
} else if (UserTrips.Any())
{
ViewBag.process = "already done";
} else if(currentTrip.TripSeats <= 0)
{
ViewBag.process = "not done";
}
var UsersTrips = _context.TripApplicationUsers.Where(t => t.ApplicationUserId.Equals(currentUser.Id)).ToList();
return View(UsersTrips);
}
public class ApplicationUser : IdentityUser
{
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string FirstName { get; set; }
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string Surname { get; set; }
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string BirthDate { get; set; }
public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
}
public class Trip
{
public int TripId { get; set; }
public string TripDate { get; set; }
public int TripDuration { get; set; }
public int TripLength { get; set; }
public int TripSeats { get; set; }
public int TrailId { get; set; }
public Trail Trail { get; set; }
public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
}
public class TripApplicationUser
{
public int TripId { get; set; }
public Trip Trip { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
If you want your Trip object to contain data from Navigational properties you have to include them in the request.
var currentTrip = await _context.Trip.Include(trip=> trip.TripApplicationUsers).FirstOrDefaultAsync(trip => trip.TripId == id);
I'm trying to bring a listing to frontEnd.
I'm using mongoDb. My mongodb has a colletion called Employee. Employee has the following attribute
public class EmployeeViewModel
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public string ownerId { get; set; }
public string atributeChange { get; set; }
public PersonalDataViewModel personalData { get; set; }
public AddressViewModel address { get; set; }
public List<EmailsViewModel> emails { get; set; }
public SyndicateViewModel syndicate { get; set; }
public List<DependentsViewModel> dependents { get; set; }
public List<PhoneViewModel> phone { get; set; }
public List<BankViewModel> bank { get; set; }
public AttributesViewModel attributes { get; set; }
public List<BenefitsViewModel> benefits { get; set; }
public TransportViewModel transport { get; set; }
public List<AttachmentsViewModel> attachments { get; set; }
public List<DocumentsViewModel> documents { get; set; }
public List<DocumentsImagesViewModel> DependentsDocuments { get; set; }
public List<AttachmentsViewModel> DependentsAttachments { get; set; }
public List<BenefitsViewModel> DependentsBenefits { get; set; }
}
In this Model, I have an attribute called: public List <DocumentsImagesViewModel> DependentsDocuments {get; set; }:
public class DocumentsViewModel
{
[BsonId]
public string ownerId { get; set; }
public string id { get; set; }
public string dependentId { get; set; }
public string number { get; set; }
public DateTime expiration { get; set; }
public List<DocumentsImagesViewModel> images { get; set; }
public List<DocumentPropertiesViewModel> properties { get; set; }
public DocumentTypeViewModel type { get; set; }
}
I'm trying to bring benefits that contain the depedentID equal of the parameter. When I use this method, it has an error that can not be converted. IEnumerable to List C #
public async Task<List<Documents>> GetDocument(string ownerId, string dependentId)
{
var query = from employee in _employee.AsQueryable()
where employee.ownerId == ownerId
select new Employee()
{
DependentsDocuments = employee.DependentsDocuments.Where(x => x.dependentId == dependentId)
};
return query.ToList();
}
What is the best way to get this data? this filter?
I used this question as a reference: Mongodb C# driver return only matching sub documents in array
LINQ's .Where returns IEnumerable<T>, your model expects a List<T>, you can either change your model to IEnumerable<T> or you can change this line of code:
DependentsDocuments = employee.DependentsDocuments
.Where(x => x.dependentId == dependentId)
to this:
DependentsDocuments = employee.DependentsDocuments
.Where(x => x.dependentId == dependentId)
.ToList()
changing your code to this one maybe it work:
public async Task<List<Documents>> GetDocument(string ownerId, string dependentId)
{
var query = (from employee in _employee.AsQueryable()
where employee.ownerId == ownerId
select new Employee()
{
DependentsDocuments = employee.DependentsDocuments.Where(x => x.dependentId == dependentId).ToList()
}).ToList();
return query.ToList();
}
I have written a controller method in asp.net api that would return a viewmodel called AllocationsViewModel. The GetAllocationsViewModel contains subsets of three more viewmodels. The GetAllocationsGrouped currently returns FIRMWIDE_MANAGER_ALLOCATION and I need to return this FirmWideAllocationsViewModel instead. I have installed Automapper 8.0 and added some code to do the mapping. Is that enough to do the job. I can see only the ManagerStrategyID and ManagerStrategyID values coming through the values are comming null for the fields. I have run the original query and can see there are values for all the fields
public class FIRMWIDE_MANAGER_ALLOCATION
{
private decimal _groupPercent;
public int FIRM_ID { get; set; }
public string FIRM_NAME { get; set; }
public int? MANAGER_STRATEGY_ID { get; set; }
public int? MANAGER_FUND_ID { get; set; }
public int MANAGER_ACCOUNTING_CLASS_ID { get; set; }
public int? MANAGER_FUND_OR_CLASS_ID { get; set; }
public string MANAGER_FUND_NAME { get; set; }
public string MANAGER_ACCOUNTING_CLASS_NAME { get; set; }
public string MANAGER_STRATEGY_NAME { get; set; }
public int? PRODUCT_ID { get; set; }
public string PRODUCT_NAME { get; set; }
public int? QUANTITY { get; set; }
public decimal? NAV { get; set; }
}
public class FirmWideAllocationsViewModel
{
private decimal _groupPercent;
public int FirmID { get; set; }
public string FirmName { get; set; }
public int? ManagerStrategyID { get; set; }
public int? ManagerFundID { get; set; }
public int ManagerAccountClassID{ get; set; }
public int? ManagerFundOrClassID { get; set; }
public string ManagerFundName { get; set; }
public string ManagerAccountingClassName { get; set; }
public string ManagerStrategyName { get; set; }
public int? ProductID { get; set; }
public string ProductName { get; set; }
public int? Quantity { get; set; }
public decimal? Nav { get; set; }
}
public IHttpActionResult Details(int id, DateTime date)
{
var viewModel = GetAllocationsViewModel(id, date);
if (viewModel == null) return NotFound();
return Ok(viewModel);
}
private AllocationsViewModel GetAllocationsViewModel(int id, DateTime date)
{
var ms = GetStrategy(id);
DateTime d = new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1);
if (ms.FIRM_ID != null)
{
var firm = GetService<FIRM>().Get(ms.FIRM_ID.Value);
var currentEntity = new EntityAllocationsViewModel(new EntityViewModel { EntityId = firm.ID, EntityName = firm.NAME, EntityType = EntityType.Firm });
var allocationsGrouped = Mapper.Map<List<FIRMWIDE_MANAGER_ALLOCATION>, List<FirmWideAllocationsViewModel>>(GetAllocationsGrouped(EntityType.ManagerStrategy, id, d).ToList());
var missingProducts = GetMissingProducts();
var vm = new AllocationsViewModel
{
CurrentEntity = currentEntity,
ManagerAllocations = allocationsGrouped,
MissingProducts = missingProducts
};
return vm;
}
return null;
}
public class AllocationsViewModel
{
public EntityAllocationsViewModel CurrentEntity { get; set; }
public List<FirmWideAllocationsViewModel> ManagerAllocations { get; set; }
public object MissingProducts { get; set; }
}
I have added the following code after installing autommapper 8.0
public class AutoMapperConfig
{
public static void Initialize()
{
Mapper.Initialize((config) =>
{
config.ReplaceMemberName("FIRM_ID", "FirmID");
config.ReplaceMemberName("FIRM_NAME", "FirmName");
config.ReplaceMemberName("MANAGER_STRATEGY_ID", "ManagerStrategyID");
config.ReplaceMemberName("MANAGER_FUND_ID", "ManagerFundID");
config.ReplaceMemberName("MANAGER_ACCOUNTING_CLASS_ID", "ManagerAccountClassID");
config.ReplaceMemberName("MANAGER_FUND_OR_CLASS_ID", "ManagerFundOrClassID");
config.ReplaceMemberName("MANAGER_FUND_NAME", "ManagerFundName");
config.ReplaceMemberName("MANAGER_ACCOUNTING_CLASS_NAME", "ManagerAccountingClassName");
config.ReplaceMemberName("MANAGER_STRATEGY_NAME", "ManagerStrategyName");
config.ReplaceMemberName("PRODUCT_ID", "ProductID");
config.ReplaceMemberName("PRODUCT_NAME", "ProductName");
config.ReplaceMemberName("QUANTITY", "Quantity");
config.ReplaceMemberName("NAV", "Nav");
config.CreateMap<FIRMWIDE_MANAGER_ALLOCATION, FirmWideAllocationsViewModel>().ReverseMap();
});
}
}
protected void Application_Start()
{
AutoMapperConfig.Initialize();
GlobalConfiguration.Configure(WebApiConfig.Register);
}
The issue has been resolved. I had to amend the grouping statement that is called to include all the fields . It was working fine earlier but with the upgrade of the latest entity framework, I think its the case
allocations = allocations.GroupBy(x => new { x.MANAGER_STRATEGY_ID, x.PRODUCT_ID, x.EVAL_DATE })
.Select(group => new FIRMWIDE_MANAGER_ALLOCATION { EVAL_DATE = group.First().EVAL_DATE,
FIRM_ID = group.First().FIRM_ID,
FIRM_NAME = group.First().FIRM_NAME,
MANAGER_ACCOUNTING_CLASS_ID = group.First().MANAGER_ACCOUNTING_CLASS_ID,
MANAGER_ACCOUNTING_CLASS_NAME = group.First().MANAGER_ACCOUNTING_CLASS_NAME,
MANAGER_FUND_ID = group.First().MANAGER_FUND_ID,
MANAGER_FUND_NAME = group.First().MANAGER_FUND_NAME,
MANAGER_FUND_OR_CLASS_ID = group.First().MANAGER_FUND_OR_CLASS_ID,
NAV = group.First().NAV,
Percent = group.First().Percent,
MANAGER_STRATEGY_ID = group.First().MANAGER_STRATEGY_ID,
EMV = group.Sum(x => x.EMV),
USD_EMV = group.Sum(x => x.USD_EMV),
MANAGER_STRATEGY_NAME = group.First().MANAGER_STRATEGY_NAME,
PRODUCT_ID = group.First().PRODUCT_ID,
PRODUCT_NAME = group.First().PRODUCT_NAME })
.ToList();
I have following three classes
Om_MembershipCharges Class
public class Om_MembershipCharges
{
[Key]
public Int32 MembershipChargesID { get; set; }
public Decimal Amount { get; set; }
public Int16 PerMonth { get; set; }
public Int16? CountryID { get; set; }
public Int16 MemebershipTypeID { get; set; }
public virtual Om_MembershipType MemebershipType { get; set; }
public virtual Om_Country Country { get; set; }
}
Om_MembershipType Class
public class Om_MembershipType
{
[Key]
public Int16 MemebershipTypeID { get; set; }
public String MemebershipType { get; set; }
public Boolean IsDefaultMembership { get; set; }
public virtual ICollection<Om_MembershipCharges> MembershipCharges { get; set; }
}
Om_Country Class
public class Om_Country
{
[Key]
public Int16 CountryID { get; set; }
public String CountryName { get; set; }
public Boolean IsActive { get; set; }
public Int16? CurrencyID { get; set; }
public Int32? MembershipChargesID { get; set; }
public virtual Om_Currency Currency { get; set; }
public Om_MembershipCharges MembershipCharges { get; set; }
}
Below is my method that fetches all the Membership Charges using MembershipCharges Property in Om_MembershipType Class. I am using Include to get the collection.
public async Task<KeyValuePair<String, Om_MembershipType>> ListByMType(String mType)
{
try
{
using (var membershipChargesContext = new DatabaseTables())
{
using (var transaction = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted },
TransactionScopeAsyncFlowOption.Enabled))
{
membershipChargesContext.Configuration.ProxyCreationEnabled = false;
var data = await membershipChargesContext
.tblMembershipType
.Where(i => i.MemebershipType == membershipType)
.Include(i => i.MembershipCharges)
.FirstOrDefaultAsync();
transaction.Complete();
return new KeyValuePair<String, Om_MembershipType>("", data);
}
}
}
catch (Exception ex)
{
var exception = ex.Message;
if (ex.InnerException != null)
exception = ex.InnerException.ToString();
return new KeyValuePair<String, Om_MembershipType>(exception, null);
}
}
Is there any way to get the Country Instance in the Membership Charges collection ?
Is there any way to get the Country Instance in the Membership Charges collection?
Yes:
var data = await membershipChargesContext
.tblMembershipType
.Where(i => i.MemebershipType == membershipType)
.Include(i => i.MembershipCharges.Select(m => m.Country))
.FirstOrDefaultAsync();
You can expand an expression in the Include statement by subsequent Select statements to include nested navigation properties.
I have this two POCO clases the Inventory and e Lot for details
How could I retrieve the data as Inventory to => Many lots
public class Inventory
{
// This determine the One to Many RelationShip
public Inventory()
{
this.Lots = new HashSet<Lot>();
}
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required]
public string ItemID { get; set; }
public string Description { get; set; }
public Nullable<DateTime> CreateDate { get; set; }
public string CreateUser { get; set; }
public decimal LastCost { get; set; }
public bool MonitorLevel { get; set; }
public short MinLevel { get; set; }
public short MaxLevel { get; set; }
public string GTIN { get; set; }
public decimal Weight { get; set; }
public string UOM { get; set; }
// Navigation Property
public virtual ICollection<Lot> Lots { get; set; }
}
public class Lot
{
public int Id { get; set; }
public Nullable<DateTime> CreateDate { get; set; }
public string CreateUser { get; set; }
public Nullable<DateTime> ExpDate { get; set; }
public string LotSerial { get; set; }
public virtual Inventory Inventory { get; set; }
}
I try this but there is an error con the conversion type
public class InventoryController : ApiController
{
private FarmStoreContext db = new FarmStoreContext();
// Project Inventory to inventory DTOs.
private IQueryable<InventoryDTO> MapInventories()
{
return from i in db.Inventories
select new InventoryDTO() { Id = i.Id, Description = i.Description, ItemID = i.ItemID, GTIN = i.GTIN, LastCost = i.LastCost, Weight = i.Weight, UOM = i.UOM};
}
public IEnumerable<InventoryDTO> GetInventories()
{
return MapInventories().AsEnumerable();
}
public InventoryDTO GetInventory(int Id)
{
Inventory inventory = db.Inventories;// <== Error - Here can not implicity convert type System.Data.Entiry.Dbset<....Models.Inventory> To ....Models.Inventory
//var inventory = (from i in MapInventories()
// where i.Id == Id
// select i).FirstOrDefault();
if (inventory == null)
{
throw new HttpResponseException(
Request.CreateResponse(HttpStatusCode.NotFound));
}
return new InventoryDTO()
{
DetaislLots = from d in inventory.Lots
select new InventoryDTO.DetaislLot()
{
LotSerial = d.LotSerial,
LIFOdate = d.LIFOdate,
QtyOriginal = d.QtyOriginal,
QtyAllocated = d.QtyAllocated,
QtyOnHand = d.QtyOnHand,
QtyAvailable = d.QtyAvailable,
Status = d.Status,
LineComment = d.LineComment,
UnitCost = d.UnitCost,
ReceiptDate = d.ReceiptDate
}
};
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
db.Inventories is a DbSet<Inventory>, which is a collection, while you are expecting a single Inventory. You have to execute a query which returns a single Inventory. Try:
Inventory inventory = db.Inventories.FirstOrDefault(i => i.Id == Id);
You basically have this query in a comment below that line. You can use the navigation property Lots on an Inventory to get the related Lot objects:
List<Lot> lots = inventory.Lots.ToList();