I have a table that holds Questions and i also have a table that has the Questions ID listed in an answers table. For sake of duplicate data i only use the id.
My question is how do i populate "in the view" the question based on an ID from the current table. They are already joined by MainQuestionID. I am using DBEntities code first.
Here is my viewModel for the page.
public class AuditFormEdit
{
public Models.MainQuestion MainQuestionID { get; set; }
public ICollection<MainQuestion> mainQuestion { get; set; }
public List<SubcategoryHelper> SubcategoryHelperGet { get; set; }
public class SubcategoryHelper : Models.SubCategory
{
public SubcategoryHelper(Models.SubCategory subCat)
{
this.SubCategoryID = subCat.SubCategoryID;
this.SubcategoryName = subCat.SubcategoryName;
}
}
public Models.MainAnswer MainAnswerInstance { get; set; }
public List<ScoreCardCheckBoxHelper> ScoreCardCheckBoxHelperList { get; set; }
public void InitializeScoreCheckBoxHelperList(List<Models.Score> ScoreList)
{
if (this.ScoreCardCheckBoxHelperList == null)
this.ScoreCardCheckBoxHelperList = new List<ScoreCardCheckBoxHelper>();
if (ScoreList != null
&& this.MainAnswerInstance != null)
{
this.ScoreCardCheckBoxHelperList.Clear();
ScoreCardCheckBoxHelper scoreCardCheckBoxHelper;
string scoreTypes =
string.IsNullOrEmpty(this.MainAnswerInstance.Score) ?
string.Empty : this.MainAnswerInstance.Score;
foreach (Models.Score scoreType in ScoreList)
{
scoreCardCheckBoxHelper = new ScoreCardCheckBoxHelper(scoreType);
if (scoreTypes.Contains(scoreType.ScoreName))
scoreCardCheckBoxHelper.Checked = true;
this.ScoreCardCheckBoxHelperList.Add(scoreCardCheckBoxHelper);
}
}
}
public void PopulateCheckBoxsToScores()
{
this.MainAnswerInstance.Score = string.Empty;
var scoreType = this.ScoreCardCheckBoxHelperList.Where(x => x.Checked)
.Select<ScoreCardCheckBoxHelper, string>(x => x.ScoreName)
.AsEnumerable();
this.MainAnswerInstance.Score = string.Join(", ", scoreType);
}
public class ScoreCardCheckBoxHelper : Models.Score
{
public bool Checked { get; set; }
public ScoreCardCheckBoxHelper() : base() { }
public ScoreCardCheckBoxHelper(Models.Score score)
{
this.ScoreID = score.ScoreID;
this.ScoreName = score.ScoreName;
}
}
}
AS you can see i am calling out an ICollection for the MainQuestions but i am not sure how to populate the questions. They also have to populate based on a sectionID.
Revised 2:51 9-21-2012
Or how would i relate the two if i displayed the list of questions and then when answering it would update the answers table and not the current shown table.
Related
I use AutoMapper 8.1.0 in a asp.net core project. I have an Automapper mapping that doesn't work as I expected. I reproduced the configuration so you can test it by yourself. So I have an ExpenseReport with a collection of ExpenseReportItem and this one with another collection. I have to keep the data of eTaxCollection after the mapping, but they are lost in the process.
So the question is why values of eTaxCollections are lost after calling _mapper.Map(vmodel, model) and how can I keep them?
The ignore attribute don't work. I also tried UseDestinationValue(). I lost 2 days trying to figure it out and I'm exhausted.
public void WeatherForecasts()
{
int[] excludeTaxes = new int[] { 2 };
var vmodel = new ExpenseReportCreateEditModel();
vmodel.Expenses.Add(new ExpenseReportItemModel()
{
ExcludeTaxIds = excludeTaxes,
Total = 12,
Id = 1
});
// fetch from bd
var model = new ExpenseReport();
// values will be lost after _mapper.Map...
var eTaxCollections = new HashSet<ExcludeExpenseReportItemTax>();
eTaxCollections.Add(new ExcludeExpenseReportItemTax()
{
TaxId = 1,
ExpenseReportItemId = 1
});
model.Items.Add(new ExpenseReportItem()
{
ExcludeTaxes = eTaxCollections,
ExpenseReportId = 1,
Id = 9
});
_mapper.Map(vmodel, model);
}
public class ExpenseReportCreateEditModelProfile : Profile
{
public ExpenseReportCreateEditModelProfile()
{
CreateMap<ExpenseReportCreateEditModel, ExpenseReport>()
.ForMember(d => d.Items, s => s.MapFrom(m => m.Expenses));
}
}
public class ExpenseReportItemModelProfile : Profile
{
public ExpenseReportItemModelProfile()
{
CreateMap<ExpenseReportItemModel, ExpenseReportItem>()
.ForMember(d => d.ExcludeTaxes, s => s.Ignore()); // <<<==== data are lost
}
}
public class ExpenseReportCreateEditModel
{
public int Id { get; set; }
public ICollection<ExpenseReportItemModel> Expenses { get; set; }
public ExpenseReportCreateEditModel()
{
Expenses = new HashSet<ExpenseReportItemModel>();
}
}
public class ExpenseReportItemModel
{
public int Id { get; set; }
public ICollection<int> ExcludeTaxIds { get; set; }
public decimal Total { get; set; }
public ExpenseReportItemModel()
{
ExcludeTaxIds = new HashSet<int>();
}
}
public class ExpenseReport
{
public int Id { get; set; }
public virtual ICollection<ExpenseReportItem> Items { get; set; }
public ExpenseReport()
{
Items = new HashSet<ExpenseReportItem>();
}
}
public class ExpenseReportItem
{
public int Id { get; set; }
public int ExpenseReportId { get; set; }
public virtual ICollection<ExcludeExpenseReportItemTax> ExcludeTaxes { get; set; }
public ExpenseReportItem()
{
ExcludeTaxes = new HashSet<ExcludeExpenseReportItemTax>();
}
}
public class ExcludeExpenseReportItemTax
{
public int ExpenseReportItemId { get; set; }
public virtual ExpenseReportItem ExpenseReportItem { get; set; }
public int TaxId { get; set; }
}
Thank you for any help
Edit
I execute the execution plan and perhaps this is the problem:
$typeMapDestination = ($dest ?? .New WebApplication1.Controllers.SampleDataController+ExpenseReportItem());
This is only way I can lost the values.
I have to find a solution now
Here the complete execution plan :
.If ($src == null) {
.Default(WebApplication1.Controllers.SampleDataController+ExpenseReportItem)
} .Else {
.Block() {
$typeMapDestination = ($dest ?? .New WebApplication1.Controllers.SampleDataController+ExpenseReportItem());
.Try {
.Block(System.Int32 $resolvedValue) {
.Block() {
$resolvedValue = .If (
$src == null || False
) {
.Default(System.Int32)
} .Else {
$src.Id
};
$typeMapDestination.Id = $resolvedValue
}
}
} .Catch (System.Exception $ex) {
.Block() {
.Throw .New AutoMapper.AutoMapperMappingException(
"Error mapping types.",
$ex,
.Constant<AutoMapper.TypePair>(AutoMapper.TypePair),
.Constant<AutoMapper.TypeMap>(AutoMapper.TypeMap),
.Constant<AutoMapper.PropertyMap>(AutoMapper.PropertyMap));
.Default(System.Int32)
}
};
$typeMapDestination
}
}
this should be a stupid problem but i dont know where to start,so i'll ask here.i've got a class named Routing which is binded to a datagrid. Inside this class theres an object from another class:
public class Routing : INotifyPropertyChanged
{
public int Sequenza { get; set; }
private ObservableCollection<Prodotti> availableProducts;
public ObservableCollection<Prodotti> AvailableProducts
{
get { return availableProducts; }
set
{
if (availableProducts != value)
{
availableProducts = value;
OnPropertyChanged("AvailableProducts");
}
}
}
private Prodotti product;
public Prodotti Product
{
get { return product; }
set
{
if (product != value)
{
product = value;
UpdateAvailableCosts();
OnPropertyChanged("Product");
}
}
}
}
and then the Product class:
public class Prodotti
{
public int Product_id { get; set; }
public string Product_description { get; set; }
public int Product_treshold { get; set; }
}
Everything works as intended,and if i just declare the "Sequenza = 1" in the routing the datagrid adds the 1 in the first row/column. But i would like to add more initial values,maybe based on data present in the database. but i cant come up with the constructor for it
Routes.Add(new Routing { Sequenza = 1,Prodotti=... });
Routes.Add(new Routing { Sequenza = 1,Prodotti= new Prodotti{Product_id =1, Product_description = "str", Product_treshold =1} });
I am having a problem where when I try to save a new entity that has existing entities nested. Instead of creating a relationship with existing entities it is duplicating them.
This is roughly my model:
public class Record
{
public int ID { get; set; }
public string RecordValue { get; set; }
public virtual ICollection<AddressLine> AddressLines { get; set; }
}
public class AddressLine
{
public int ID { get; set; }
public string AddressLineValue { get; set; }
public virtual ICollection<AddressLineType> AddressLineTypes { get; set; }
}
public class AddressLineType
{
public int ID { get; set; }
public string AddressLineTypeValue { get; set; }
}
I don't want any duplicate AddressLineTypes added so in my code I am doing something like this:
public void button1_Click(object sender, EventArgs e)
{
Record r = new Record();
r.RecordValue = "Record value";
AddressLine al = new AddressLine();
al.AddressLineValue = "Address line value";
AddressLineType alt;
using (var db = new MyDbContext())
{
alt = db.AddressLineTypes.Single(x => x.Value == "TypeValue");
}
al.AddressLineTypes.Add(alt);
r.AddressLines.Add(al);
SaveRecord(r);
}
public void SaveRecord(Record r)
{
using (var db = new MyDbContext())
{
db.Records.Add(r);
db.SaveChanges();
}
}
I have hit a breakpoint before db.SaveChanges() and the AddressLineType ID is populated but it creates new entries in the database as if ID == 0.
How do I stop the existing AddressLineTypes duplicating on save?
Try using a single Context:
...
using (var db = new MyDbContext())
{
alt = db.AddressLineTypes.Single(x => x.Value == "TypeValue");
al.AddressLineTypes.Add(alt);
r.AddressLines.Add(al);
SaveRecord(r, db);
}
}
public void SaveRecord(Record r, MyDbContext db)
{
db.Records.Add(r);
db.SaveChanges();
}
Its first time when I'm using ORM.
Here is my code:
public class EwidencjonowanaRzeczMap : ClassMap<EwidencjonowanaRzecz>
{
public EwidencjonowanaRzeczMap()
{
Id(c => c.Id);
References(m => m.WagaRef);
}
}
public class WagaMap : ClassMap<Waga>
{
public WagaMap()
{
Id(m => m.Id);
Map(m => m.WagaPrzedmiotu);
HasMany(m => m.ListaRzeczy).Inverse().Cascade.All();
}
}
public class EwidencjonowanaRzecz
{
public virtual int Id { get; set; }
public virtual Waga WagaRef { get; set; }
}
public class Waga
{
public virtual int Id { get; set; }
public virtual String WagaPrzedmiotu { get; set; }
public virtual IList<EwidencjonowanaRzecz> ListaRzeczy { get; set; }
public Waga()
{
ListaRzeczy = new List<EwidencjonowanaRzecz>();
}
}
Here is my function to select records:
public IList<T> SelectAllFromTable<T>()
{
IList<T> czyDanePoprawne = null;
try
{
_sesja = NHibernateHelper.CreateSessionFactory().OpenSession();
using (_sesja.BeginTransaction())
{
czyDanePoprawne = _sesja.CreateCriteria(typeof(T)).List<T>();
}
}
catch (Exception)
{
CzyNieWystapilyBledy = true;
}
return czyDanePoprawne;
}
Tables:
ewidencjonowanarzecz [ Id - PK , IdWagi - FK (Waga.Id)]
waga [ Id - PK , WagaPrzedmiotu ]
Every type Id's - INT(3)
WagaPrzedmiotu is VARCHAR(10)
How to read to list these 2 fields?:
Id (ewidencjonowanarzecz) and WagaPrzedmiotu (waga)
In my mapping:
EwidencjaList = ModelBazy.SelectAllFromTable<EwidencjonowanaRzecz>();
is empty.
What is wrong with my mapping?
If you want to select the table record you can try this :
_sesja = NHibernateHelper.CreateSessionFactory().OpenSession();
var tabledata = _sesja.CreateQuery("from EwidencjonowanaRzecz").List<EwidencjonowanaRzecz>();
If you want to check whether if it fetches the values, try this
string value = tabledata.WagaPrzedmiotu;
I have a problem, when i add a new entity of SessionImages, and then add another one (By uploading it), it gets doubled.
For example :
Adding an image :
Adding another one afterwards :
Here's my controller code :
[HttpPost]
public ActionResult SessionImages(FormCollection collection)
{
int SessionID = Convert.ToInt32(collection[0]);
Sessions SessionModel = sessionsRepo.GetSessionById(SessionID);
bool uploadSucceded = Utility.Utility.UploadImages(this, Request.Files, Server.MapPath(Path.Combine("~/Photos/Sessions", SessionModel.Name)));
for (int i = 0; i < Request.Files.Count; i++)
{
if (Request.Files[i].ContentLength == 0)
{
continue;
}
SessionImages ImageModel = new SessionImages
{
Name = Request.Files[i].FileName,
Path = Path.Combine("~/Photos/Sessions/", SessionModel.Name, "actual", Request.Files[i].FileName),
Session = SessionModel,
SessionID = SessionID
};
sessionImagesRepo.Add(SessionModel, ImageModel);
}
return RedirectToAction("SessionImages",SessionModel.ID);
}
Here's the sessionImagesRepo.Add method :
public SessionImages Add(Sessions SessionModel, SessionImages ImageModel)
{
try
{
context.Entry(ImageModel).State = System.Data.EntityState.Added;
SessionModel.PhotosCount = SessionModel.Images.Count;
context.Entry(SessionModel).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
catch
{
return null;
}
return ImageModel;
}
Here's my entities :
namespace FP.Domain.Entities
{
public class Sessions
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime Date { get; set; }
public int PhotosCount { get; set; }
public string CoverPhoto { get; set; }
public List<SessionImages> Images { get; set; }
}
}
namespace FP.Domain.Entities
{
public class SessionImages
{
public int ImageID { get; set; }
public string Name { get; set; }
public string Path { get; set; }
public int SessionID { get; set; }
public Sessions Session { get; set; }
}
}
Here's the configuration :
namespace FP.Domain.Configurations
{
public class SessionsConfig : EntityTypeConfiguration<Sessions>
{
public SessionsConfig()
{
ToTable("Sessions");
Property(p => p.Name).IsRequired();
Property(p => p.PhotosCount).IsRequired();
Property(p => p.CoverPhoto).IsRequired();
Property(p => p.Date).HasColumnType("date");
}
}
}
namespace FP.Domain.Configurations
{
public class SessionImagesConfig : EntityTypeConfiguration<SessionImages>
{
public SessionImagesConfig()
{
ToTable("SessionImages");
HasKey(e => e.ImageID);
Property(p => p.Path).IsRequired();
HasRequired(i => i.Session)
.WithMany(s => s.Images)
.HasForeignKey(i => i.SessionID);
}
}
}
Try changing the repository method like this:
public SessionImages Add(Sessions SessionModel, SessionImages ImageModel)
{
try
{
SessionModel.Images.Add(ImageModel);
SessionModel.PhotosCount = SessionModel.Images.Count;
context.Entry(SessionModel).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
catch
{
return null;
}
return ImageModel;
}
And in the action remove the line that I've commented:
SessionImages ImageModel = new SessionImages
{
Name = Request.Files[i].FileName,
Path = Path.Combine("~/Photos/Sessions/", SessionModel.Name, "actual", Request.Files[i].FileName),
//Session = SessionModel,
SessionID = SessionID
};
I'd suggest you drop these lines, if you can workaround it (I can see the point though, in the count)...
context.Entry(ImageModel).State = System.Data.EntityState.Added;
SessionModel.PhotosCount = SessionModel.Images.Count;
context.Entry(SessionModel).State = System.Data.EntityState.Modified;
That's probably what's messing with it. I've seen similar problems more than once - and then I usually end up doing quite the opposite:
context.Entry(Parent).State = System.Data.EntityState.Unchanged;
Everything you're doing there is to get the Count working.
I can understand the optimization reasons, but you do have that count in the collection inherently. I know this is faster if you don't want to load etc.
I'm not sure what to suggest - but I'm suspecting that to be the 'culprit'.
Try w/o it, turn off and disregard count while testing. See what
happens. If that's it, then think about how to reorganize that a bit.