'System.Reflection.TargetInvocationException' occurred in EntityFramework.SqlServer.dll - c#

I'm calling this method by CascadingDropDownListFor and I'm getting an exception:
An exception of type 'System.Reflection.TargetInvocationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
public JsonResult GetRaca(string especieId)
{
int esp = Convert.ToInt32(especieId);
var rac = db.Raca.Where(c => c.EspecieId == esp).ToList();
var racas = new List<SelectListItem>();
foreach (var ra in rac)
{
var racaConteudo = db.RacaConteudo
.Where(c => c.RacaId == ra.RacaId)
.Where(c => c.IdiomaId == 1)
.First(); // <= The exception occurred here
racas.Add(new SelectListItem
{
Text = racaConteudo.RacaId.ToString(),
Value = racaConteudo.NomePopular
});
}
return Json(racas, JsonRequestBehavior.AllowGet);
}
The entity:
[Table("RacasConteudo")]
public class RacaConteudo
{
public RacaConteudo(long RacaId, string NomeCientifico, string NomePopular, long IdiomaId)
{
this.RacaId = RacaId;
this.NomeCientifico = NomeCientifico;
this.NomePopular = NomePopular;
this.IdiomaId = IdiomaId;
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long RacaConteudoId { get; set; }
[ForeignKey("RacaId")]
public virtual Raca Raca { get; set; }
public long RacaId { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Nome Cientifico")]
public string NomeCientifico { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Nome Popular")]
public string NomePopular { get; set; }
[ForeignKey("IdiomaId")]
[Display(Name = "Idioma")]
public virtual Idioma Idioma { get; set; }
public long IdiomaId { get; set; }
}

Remove parameterized constructor public RacaConteudo(long RacaId, ..., long IdiomaId), and make the class partial.
[Table("RacasConteudo")]
public partial class RacaConteudo
^^^^^
{
/* public RacaConteudo(...) {} */
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long RacaConteudoId { get; set; }
....
}
Based on your updated question, Raca and RacaConteudo have relationship.
If so, you could even retrieve the desired result in single query which is a lot faster than querying multiple RacaConteudos for each and every Raca.
public JsonResult GetRaca(string especieId)
{
int esp = Convert.ToInt32(especieId);
var result = (from c in db.RacaConteudo
where c.Raca.EspecieId == esp && c.IdiomaId == 1
select new {Text = c.NomePopular, Value = c.RacaId.ToString()}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}

Related

Add values to a list inside a list Linq

I am having a class like this.
public class CameraModel
{
public int JobId { get; set; }
public int ViewId { get; set; }
public Guid ViewGuid { get; set; }
public string Name { get; set; }
public int ViewNum { get; set; }
public int LayoutID { get; set; }
public List<CameraViewItemModel> CameraViewItems { get; set; }
}
The CameraViewItemModel class is like this:
public class CameraViewItemModel
{
public int JobID { get; set; }
public Guid ViewGuid { get; set; }
public int ViewID { get; set; }
public int CamNum { get; set; }
public Guid ChannelGuid { get; set; }
public string Name { get; set; }
public ActionType Action { get; set; }
}
Now, I am assigning the list of CameraViewItemModel like this:
// get all the cameramodel's
cameraModels = _unitOfWork.Context.CameraViews.Where(m => m.JobId == siteId)
.Select(m => new CameraModel
{
JobId = m.JobId,
ViewId = m.ViewId,
ViewGuid = m.ViewGuid,
Name = m.Name,
ViewNum = m.ViewNum,
LayoutID = m.LayoutId
}).ToList();
// get all the cameraviewitemmodels
cameraViewItemModels =
(from cameraView in _unitOfWork.Repository<CameraViews>().Get(x => x.JobId == siteId).Result
join cameraViewItem in _unitOfWork.Repository<CameraViewItems>().Get(x => x.JobId == siteId)
.Result on cameraView.ViewId equals cameraViewItem.ViewId into CameraViewItemResults
from cameraViewItemResult in CameraViewItemResults.DefaultIfEmpty()
join cameraChannel in _unitOfWork.Repository<CameraChannels>().Get(x => x.JobId == siteId)
.Result on (cameraViewItemResult == null ? new Guid() : cameraViewItemResult.ChannelGuid) equals cameraChannel.ChannelGuid into CameraChannelResults
from cameraChannelResult in CameraChannelResults.DefaultIfEmpty()
select new CameraViewItemModel
{
JobID = cameraView.JobId,
ViewID = cameraView.ViewId,
ViewGuid = cameraView.ViewGuid,
CamNum = cameraViewItemResult.CamNum,
ChannelGuid = cameraChannelResult.ChannelGuid,
Name = cameraChannelResult.Name
}).ToList();
// then do a 'join' on JobId, ViewId and ViewGuid and assign the list of cameraviewitemmodels to cameraModels.
foreach (var cameraModel in cameraModels)
{
cameraModel.CameraViewItems = (from cameraViewItem in cameraViewItemModels
where cameraModel.JobId == cameraViewItem.JobID
&& cameraModel.ViewId == cameraViewItem.ViewID
&& cameraModel.ViewGuid == cameraViewItem.ViewGuid
select cameraViewItem).ToList();
}
return cameraModels;
There are three tables in database:
CameraViews, CameraViewItems, CameraChannels.
CameraViews is the main table. It is left joined with CameraViewItems and CameraChannels to get the desired result. There may not be any data in CameraViewItems and CameraChannels for a corresponding CameraView.
Is it possible to assign the list of CameraViewItemModels to CameraModels in a single linq statement.
Here is a simple way to add values to a sub list, dunno if this is what you mean. You can keep selecting sub lists if that is necessary.
var parent_lst = new List<List<string>>(); // Root/parent list that contains the other lists
var sub_lst = new List<string>(); // Sub list with values
var selected_parent_lst = parent_lst[0]; // Here I select sub list, in this case by list index
selected_parent_lst.Add("My new value"); // And here I add the new value

ModelState Error c# mvc5

In an Action Result that does a HttpPost i get an error from EF
"ModelState.Errors Internal error in the expression evaluator"
My model in View is OrdineOmaggio
public partial class OrdineOmaggio
{
public int Id { get; set; }
public string Id_Gioielleria { get; set; }
public System.DateTime Data_Ordine { get; set; }
public virtual Consumatore MD_CONSUMATORE { get; set; }
public virtual Omaggio MD_OMAGGIO { get; set; }
public virtual CodiceRandomConsumatore MD_RANDOM_CONSUMATORE { get; set; }
}
My Action is so
public async Task<ActionResult> ChooseGift(
[Bind(Include ="Data_Ordine,MD_RANDOM_CONSUMATORE,MD_OMAGGIO,Id_Gioielleria")]
OrdineOmaggio ordineOmaggio,
string codiceOmaggio, string codice)
{
var randomConsumatore = _context.CodiciRandomConsumatori
.SingleOrDefault(c => c.Codice == codice) ??
new CodiceRandomConsumatore
{
Id = -1,
Codice = "",
Assegnato = null,
Distinzione = ""
};
var consumatore = _context.CodiciRandomConsumatori
.Where(c => c.Codice == codice)
.Select(c => c.MD_CONSUMATORE)
.SingleOrDefault();
var omaggio = _context.Omaggi
.SingleOrDefault(c => c.CodiceOmaggio == codiceOmaggio);
if (ModelState.IsValid)
{
ordineOmaggio.Data_Ordine = DateTime.Now;
ordineOmaggio.Id_Gioielleria = ordineOmaggio.Id_Gioielleria;
ordineOmaggio.MD_CONSUMATORE = consumatore; // FK
ordineOmaggio.MD_OMAGGIO = omaggio; // FK
ordineOmaggio.MD_RANDOM_CONSUMATORE = randomConsumatore; // FK
_context.OrdiniOmaggio.Add(ordineOmaggio);
randomConsumatore.Assegnato = true;
_context.SaveChanges();
return RedirectToAction("Success");
}
return View(ordineOmaggio);
}
The error is about dataAnnotation: it say that not all field all filled
The metadata is
public class OrdineOmaggioMetadata
{
[Required(ErrorMessage = "Scegli la gioiellereia.")]
public string Id_Gioielleria;
[Required(ErrorMessage = "Seleziona una foto.")]
public Omaggio MD_OMAGGIO;
...
}
In my view i placed
#Html.HiddenFor(m=> m.MD_OMAGGIO.CodiceOmaggio)
#Html.ValidationMessageFor(m => m.MD_OMAGGIO.CodiceOmaggio)
but this helper pass null to ActionResult
MD_OMAGGIO is a table foreign key for product codes.
what i wrong ?

How do I create and insert one-to-many object with entity framework c#

I'm trying to create an object and insert to the database but keep getting the same error no matter what I try.
The row that I get the error on is ColumnGroupTest.ValidValues.Add(memberComment1); the error is
error message
NullReferenceException was unhandled by user code
my models
public class StoreColumnName
{
public int Id { get; set; }
public string StoreColumnGroupName { get; set; }
public string ColumnName { get; set; }
public string ColumnType { get; set; }
public List<StoreValidValue> ValidValues { get; set; }
}
public class StoreValidValue
{
public int Id { get; set; }
public string ValidValue { get; set; }
public StoreColumnName StoreColumnName { get; set; }
}
my controller
public ActionResult Index()
{
XDocument document = XDocument.Load(#"C:\Users\Physical.xml");
var result = document.Descendants("ColumnGroup");
foreach(var item in result){
var ColumnGroupName = item.Attribute("name").Value;
var Columns = item.Descendants("Column");
foreach (var itemColumn in Columns)
{
StoreColumnName ColumnGroup = new StoreColumnName();
var ColumnGroupTest = new StoreColumnName
{
StoreColumnGroupName = ColumnGroupName,
ColumnName = itemColumn.Attribute("name").Value,
ColumnType = itemColumn.Attribute("type").Value,
Id = 11
};
var ValidValues = itemColumn.Descendants("ValidValues");
var Values = ValidValues.Descendants("Value");
foreach (var Value in Values)
{
var memberComment1 = new StoreValidValue
{
StoreColumnName = ColumnGroupTest,
ValidValue = Value.Value,
Id = 101
};
ColumnGroupTest.ValidValues.Add(memberComment1);
}
}
}
return View();
}
(I gladly take tips on what I can improve when asking for help/guiding here).
Can anyone help ?
The issue that you're having is that you don't initialize your ValidValues property to a list. By default, those types of properties initialize to null unless you specify differently.
The best approach is to add that initialization to your constructor of that object.
public StoreColumnName() {
this.ValidValues = new List<StoreValidValue>();
}

Request.CreateResponse returns blank data to postman

I have encountered a problem when trying to call my web api with a post request, a empty array is returned.
My method is:
// POST: Api/v1/transaction/
[HttpPost]
public HttpResponseMessage Post(string user)
{
var userId = new Guid(user);
var transactions = new Collection<TransactionDataTransferObject>();
try
{
var seller = _databaseContext.Sellers.Single(s => s.Id == userId);
var sellerMedias = _databaseContext.Medias.Where(m => m.TakenBy.Id == seller.Id);
foreach (var sellerMedia in sellerMedias)
{
var allLogsForMedia = _databaseContext.Logs.Where(l => l.ObjectReferenceId == sellerMedia.Id);
foreach (var logMedia in allLogsForMedia)
{
var transaction = new TransactionDataTransferObject
{
Date = logMedia.DateTimeInUtc,
Amount = sellerMedia.PriceInSek,
MediaName = sellerMedia.FileName,
UserName = seller.FirstName + " " + seller.LastName
};
transactions.Add(transaction);
}
}
}
catch (Exception exception)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, exception);
}
return Request.CreateResponse(HttpStatusCode.OK, transactions);
}
When I debug transactions variable, I see two objects in the collection.
My response to postman is
[
{},
{}
]
What have I done wrong? Where is my data which is sent?
Ok, after some hours of slaming my head in the table i found out that I used
[DataContract] as filter on the ViewModel,TransactionDataTransferObject.
Like this:
[DataContract]
public class TransactionDataTransferObject
{
[Display(Name = "Date")]
public DateTime Date { get; set; }
public string MediaName { get; set; }
public Guid MediaId { get; set; }
public string UserName { get; set; }
public Guid UserId { get; set; }
[Display(Name = "Description")]
public string Discriminator { get; set; }
[Display(Name = "Amount")]
public decimal Amount { get; set; }
}
Which was wrong in this case...
Thanks for reading!

Entity Framework is deleting an Entry

I'm fetching information from a webpage in two pages:
First page:
- Content c1 is created and a Translation c1.t1 is created;
- Content c2 is created and Translation c2.t1 is created;
Second page:
- The system detects that c1 already exists and just adds c1.t2 to the proper table;
- The system detects that c2 already exists and just adds c2.t2 to the proper table;
Somehow, on the second page, the system is overritting c1.t1 with c1.t2 and only the second translation is available on the database. When debbugging, found that it is deletting c1.t1 at some point but I couldn't figure out why.
This is my actual stuff:
EF 4.1
Code-First Aproach
DbContext
I have this POCO Entities (minimized):
RegionalContent: - It's like a tranlation and regional info about a content:
public class XBLRegionalContent
{
[Key, Column(Order = 0)]
public string ContentId { get; set; }
[ForeignKey("ContentId")]
public virtual XBLContent Content { get; set; }
[Key, Column(Order = 1)]
public string RegionId { get; set; }
[ForeignKey("RegionId")]
public virtual XBLRegion Region { get; set; }
public string Name { get; set; }
}
Content: - Unique content per GUID:
public class XBLContent
{
#region [ Properties ]
/// <summary>
/// The GUID
/// </summary>
[Key]
[StringLength(36, ErrorMessage="Must have 36 characters")]
[Required(ErrorMessage="Must have a unique GUID")]
public string GUID { get; set; }
public string Type { get; set; }
public virtual ICollection<XBLRegionalContent> RegionalInfo { get; set; }
}
Region - Pretty straight forward:
public class XBLRegion
{
[Key]
[StringLength(5, ErrorMessage="ID must have 5 characters")]
[Required]
[RegularExpression(#"[a-z]{2}-[A-Z]{2}", ErrorMessage = "ID must be in ISO 639 standard")]
public string ID { get; set; }
public string Country { get; set; }
public string Language { get; set; }
}
DbContext class has nothing different, just DbSets.
One content has many translations. One translation has one content related. The translation primary key is compound of content guid and region id.
I have a class in Model that populates the database and creates a local list that the View uses to display information. That way, I only access the Database one time to save, and don't need to retrieve information when it is saved.
Here is only the important information about this class:
public class XBLChart : IDisposable
{
XBLContentContext db = new XBLContentContext();
private string baseurl = "http://foo.bar/";
public string Locale { get; private set; }
public string HTML { get; private set; }
public string URL { get; set; }
public ContentType Type { get; private set; }
public List<XBLContent> Contents { get; set; }
public XBLChart(ContentType type, string sort, string locale)
{
Type = type;
if (sort == null)
sort = Enum.GetName(typeof(SortBy), SortBy.OfferStartDate);
if (locale != null && locale.Length == 5)
Locale = locale;
else
Locale = "en-US";
URL = baseurl + Locale + "/" + sort;
HTML = FeedUtils.RequestHTML(URL);
Contents = new List<XBLContent>();
PopulateList();
}
private void PopulateList()
{
MatchCollection itens = Regexes.ChartItems().Matches(HTML);
MatchCollection titulos = Regexes.ChartTitles().Matches(HTML);
int type = (int)Type;
int start = type * 12;
this.Title = HttpUtility.HtmlDecode(titulos[type].Groups["title"].Value);
if (titulos.Count < 8 && start > 1)
{
start = (type - 1) * 12;
type--;
}
XBLRegion region;
if (!db.XBLRegions.Any(x => x.ID == Locale))
{
region = new XBLRegion { ID = Locale };
db.XBLRegions.Add(region);
db.SaveChanges();
}
else
region = db.XBLRegions.SingleOrDefault(x => x.ID == Locale);
for (int i = start; i < (start + 2); i++)
{
string guid = itens[i].Groups["guid"].Value;
XBLContent c = new XBLContent(guid);
if (!db.XBLContents.Any(x => x.GUID == guid))
{
c.Type = Type.ToString();
c.PopularInfo(Locale);
db.XBLContents.Add(c);
}
else
c = db.XBLContents.Single(x => x.GUID == c.GUID);
XBLRegionalContent regionalcontent = new XBLRegionalContent(guid, Locale);
if (!db.XBLRegionalInfos.Any(x => x.ContentId == guid && x.RegionId == Locale))
{
if (c.HTML == null)
c.PopularInfo(Locale);
regionalcontent.Populate(c.HTML);
regionalcontent.Name = HttpUtility.HtmlDecode(itens[i].Groups["name"].Value);
db.XBLRegionalInfos.Add(regionalcontent);
}
else
regionalcontent = db.XBLRegionalInfos.Single(x => x.ContentId == guid && x.RegionId == Locale);
db.SaveChanges();
c.RegionalInfo.Clear();
regionalcontent.Region = region;
c.RegionalInfo.Add(regionalcontent);
Contents.Add(c);
}
}
}
you are missing a db.SaveChanges() after
db.SaveChanges();
c.RegionalInfo.Clear();
regionalcontent.Region = region;
c.RegionalInfo.Add(regionalcontent);

Categories