EF4. Add a object with relationship causes full table select - linq

Ex 1:
"autor.ComentariosWorkItens.Add(comentarioWorkItem);"
autor.ComentariosWorkItens makes EF4 load all ComentariosWorkItens.
Ex 2:
comentarioWorkItem.Usuario = autor;
Fixup make EF load all ComentariosWorkItens too:
private void FixupUsuario(Usuario previousValue)
{
if (previousValue != null && previousValue.ComentariosWorkItens.Contains(this))
{
previousValue.ComentariosWorkItens.Remove(this);
}
if (Usuario != null)
{
if (!Usuario.ComentariosWorkItens.Contains(this))
{
Usuario.ComentariosWorkItens.Add(this);
}
}
}
How can I prevent this?

1: Turn it around:
comentarioWorkItem.Usario = autor;
2: How is the EF supposed to answer this:
previousValue.ComentariosWorkItens.Contains(this)
... without looking into ComentariosWorkItens?

I sent a email to Julie Lerman. Here her answer:
"I think this is known (and AWFUL) behavior on EF’s part. I’m not sure what to tell you.
You might want to take a look in the MSDN forums to see if anyone from the team has anything to say about it.
And, since I’m in the middle of reviewing my book before it goes to print, I will check to be sure I have a warning about this in there somewhere!"

Related

Laravel 5.5 - findorFail and check for another value

I am using try in Laravel 5.5 like this...
try {
$fruit = Fruit::findOrFail($id);
}
But I would like to check that not only that it finds the Fruit with the supplied ID but that it also has a fruit_color of 'red'
Do I need to do this with a 'with' statement?
I know I can run another check afterwards but wondered if I could do this all in one statement?
A few things. First, throwing an exception here is the wrong way to handle the ‘if’ situation. If you plan on a situation where a value isn’t return, then this isn’t the proper use of an exception. To answer your question:
$fruit = Fruit::where(‘id’, $id)->where(‘color’, ‘red’)->get();
This returns a collection of items meeting your criteria. Next to test if the collection is empty (no fruit) you can do the following:
if($fruit->isEmpty()) {
//handle empty collection
}
Hope this helps! The Laravel documents for collections kicks a**. I’d recommend reading further there.
You just need to add your extra conditions in before you call the find:
try {
$fruit = Fruit::where('fruit_color', 'red')->findOrFail($id);
}
Try this code
$fruit = Fruit::where(‘id’, $id)->where(‘color’, ‘red’)->first();

Grails: Constraints: Database to allow nulls, but forms may not be blank

I have a domain object called OurCompany and I'd like to be able to deliberately insert a row mostly full of nulls. When a user fills in a form though, I'd like to validate it and not allow blanks.
class OurCompany {
static constraints = {
enterpriseName blank:false, nullable:true
}
String enterpriseName
static belongsTo = [measurement:Measurement]
}
When I create the empty row in the database, I turn off validation and it works fine.
ourCompany = new OurCompany();
measurement.addToOurCompany(ourCompany).save(validate:false);
Later, when I update the row, the validation is ignored and the record saves even though there is a null / blank value.
def ourCompany = loadOrCreateOurCompany();
def industrySectors = loadIndustrySectors();
bindData (ourCompany, params)
ourCompany.validate()
if (ourCompany.hasErrors()) {
ourCompany.errors.allErrors.each {
println(it)
}
} else {
ourCompany.save();
}
How do I tell grails that I'd like the DATABASE to accept nulls, but when validating, not allow nulls or blanks?
That's what Command Objects are for
The solution (so far) REALLY ugly. It seems that there is no way to make a grails domain property BOTH nullable and have a CONSTRAINT. The only way to do it is to use a Command Object to do the validation against. In my opinion, it's really quite a painful solution and a rather inelegant, poorly documented methodology. This has been my most unpleasant grails experience.

OSDictionary * Injection in IORegistry

I'm trying to create a new Dictionary and inject it in the IORegistry. I've managed to inject simple strings or data values but thats it.
My approach is via a modified IOPCIFamily.kext, and it's not for a specific purpose but just for learning.
My code for 1 line values is something like this
if (product == id){ setProperty("test", "test") }
and another approach
if (product == id){ propTable->setObject("TEST", prop) prop->release(); }
propTable is the Parent Dictionary, so i must create a child Dictionary to which i can inject values with setObject parameter.
Does anyone have an idea on how to do this? I suspect it must be something like this:
propTable->newTable->setObject(etc)
but i didn't figure how to create the newTable for propTable to insert it in the existing one of what ever product == ids it finds.
Thank you very much, sorry if it's confusing. Not used to explain code related stuff in english.
If I understand your question correctly, you want the OSDictionary::withCapacity factory function.
For example:
OSDictionary* prop_dict = OSDictionary::withCapacity(1);
OSString* val = OSString::withCString("test");
if (!prop_dict || !val)
{
// handle error...
}
prop_dict->setObject("test", val);
val->release(); val = NULL;
and then, to use it in you property table:
propTable->setObject("NewProperty", prop_dict);
prop_dict->release(); prop_dict = NULL;

ABCpdf Table Help

First time poster so please bear with me. Basically I have a pdf document that I am creating on the fly using ABCpdf (via C# project) however the table rows seem to be rendering on top of each other. I have looked at all the documentation etc and searched for an answer but have not found anything relating to this.
I referred to the examples on creating tables which got me to the point I am at now but I cannot understand what is causing this issue. Below is an example of how I am constructing my table. Any help offered would be greatly appreciated. I have created a wrapper for ABCpdf to make it quicker and more code efficient to use but cannot see this causing the issue as it simply calls the same code as it would if I wrote it all out line by line.
PdfTable pdfTable = new PdfTable(_abcPdfWrapper.PdfDocument, 5, 3) {HorizontalAlignment = 1};
pdfTable.NextRow();
pdfTable.NextCell();
pdfTable.AddText(firstStageReference);
pdfTable.NextCell();
pdfTable.AddText(String.Format("{0:#,0.000}", materialWeight) + " Kg");
pdfTable.NextRow();
pdfTable.AddText(weighDepartmentMaterial.sMaterialCode ?? String.Empty);
pdfTable.NextCell();
pdfTable.AddText(weighDepartmentMaterial.sMaterialName ?? String.Empty);
pdfTable.NextCell();
pdfTable.AddText(String.Format("{0:#,0.000}", materialWeight) + " Kg");
pdfTable.NextCell();
pdfTable.AddText(weighDepartmentMaterial.Scale ?? String.Empty);
pdfTable.NextCell();
pdfTable.AddText(weighDepartmentMaterial.AddGroup ?? String.Empty);
There is other code in between these lines but they bear no significance to the construction of the table other than a loop in which the lines from number 2 down are contained to loop through a series of raw materials and create a row for each.
I solved this issue in the end by simply adding these two functions into my wrapper class and then calling them before and after using the table object.
public void PdfTableBegin()
{
PdfDocument.TopDown = false;
}
public void PdfTableEnd()
{
PdfDocument.TopDown = true;
}

Subsonic 3 Newtonsoft JSON "Self referencing loop Exception"

Hi I been searching for my error but I can't find anything that help me. The problem is this. I been working with Subsonic 3, Newtonsoft Json and the linq way of write so I have this easy query:
var found = from client in newclients.All() where client.Period == "sometext" select client;
string periodoJSON = JsonConvert.SerializeObject(periodoFound); //this get "Self referencing loop Exception"
the problem is when I run this script I get the horrible exception "Self referening loop exception" in the JsonConvert line, subsonic have all the objects without any problem but if I do the following.
var found = from client in newclients.All() where client.Period == "sometext" select new client{client.Name, client.LastName, etc};
string periodoJSON = JsonConvert.SerializeObject(periodoFound);
I get the object serialize with a any problem with all the properties. I'm doing the last way because I have to finish my work but is any other way or solution for this problem, if not I will have to write all the properties every time I want to get a full table properties.
hope any can solve my problem o help me in the path for find a solution....
what I have is a really basic query with linq and I try the three values for JsonSerializerSettings and any work, again I'm working with subsonic 3 this not happend either with subsnoic 2 and I can make it work if I specify one by one the properties of the object in the linq query does any have any clue of what is happend, ANY more help would be great!!! If I put the value of Serialize my page get crazy and in a infinity loop state, if I decide for error simple doesn't work and Ignore nothing happen... some more information about this self referencia loop?
var u = usuario.SingleOrDefault(x => x.TipoUsuario == "A" || x.TipoUsuario == "W");
JsonSerializerSettings setting = new JsonSerializerSettings();
setting.ReferenceLoopHandling = ReferenceLoopHandling.Error; //.Serialize .Ignore
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"usuario", "var usuario=" + JsonConvert.SerializeObject(u, Formatting.None, setting) + ";");
Update ------
I code the following
string jsU = JsonConvert.SerializeObject(u,Formatting.None,new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
and is workign but the only thing wrongs is that in the json object comes all the information about the columns of subsonic 3 and a BIG chunk of text explain it... does any one know how to not SEND this part of the object??
Without knowing more about you object model it is hard to provide a definitive answer, but I would take a look at the ReferenceLoopHandling enum.
You're calling string SerializeObject(object value) on JsonConvert. Try the string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings) method instead. The JsonSerializerSettings settings parameter lets you set a bunch of things, including the ReferenceLoopHandling ReferenceLoopHandling { get; set; } property.
You can try these values:
public enum ReferenceLoopHandling
{
Error,
Ignore,
Serialize
}
Obviously, Error is the default and that's what you're getting. Perhaps one of the others will help.

Resources