Sunday, 26 August 2018

Entity Framework saves only one child of my POCO entity (the HashSet concept)

I was trying to create an entity with several children entities and persist it to the database using Entity Framework. I was generating the entity, set its entry state to Added, saved the changes in the DbContext, everything right. However, in the database I had one parent entity and one child entity. I suspected it had something to do with the way I created the tables, the foreign keys, something related to the way I was declaring the connection between the entities in the model. It was none of that.

If you look at the way EF generates entities from database tables, it creates a two directional relationship from any foreign key: the parent entity gets an ICollection<Child> property to hold the children and the child entity a virtual property of type Parent to hold the parent. Moreover, the parent entity instantiates the collection in the constructor in the form of a HashSet<Child>. It doesn't have to be a HashSet, though. It works just as well if you overwrite it when you create the entity with something like a List. However, the HashSet approach tells something important of the way EF behaves when considering collections of child objects.

In my case, I was doing something like
var parent = new Parent { 
Children = Enumerable
.Repeat(new Child { SomeProperty = SomeValue }, 3)
.ToList()
};
Can you spot the problem? When I changed the code to
var parent = new Parent();
Enumerable
.Repeat(new Child { SomeProperty = SomeValue }, 3)
.ToList()
.ForEach(child => parent.Children.Add(child));
I was shocked to see that my Parent had only a list of Children with count 1. Why? Because Enumerable.Repeat takes the instance of the object you give it and repeats it:

Enumerable.Repeat(something,3).Distinct().Count() == 1 !

There was no problem that I was setting the Children collection to a List instead of a HashSet, but when saving the children, Entity Framework was considering the distinct instances of Child.

The solution here was to generate different instances of the same object, something like
var parent = new Parent {
Children = Enumerable.Range(0,3)
.Select(i => new Child { SomeProperty = SomeValue }, 3)
.ToList()
};
or, to make it more clear for this case:
var parent = new Parent {
Children = Enumerable
.Repeat(() => new Child { SomeProperty = SomeValue }, 3)
.Select(generator => generator())
.ToList()
};

Thursday, 23 August 2018

Sapiens: A Brief History of Humankind, by Yuval Noah Harari

book cover In 2014 Yuval Noah Harari became world wide famous for the English publication of his book Sapiens: A Brief History of Humankind. A lot of my friends recommended it, I couldn't turn around without hearing about it, but before I could read it, I watched some videos and TED talks from the guy so I was hearing the slightly whiny voice and I was imagining the face and mannerism of Harari while I was reading the book. And the truth is the book feels just like an extended version of one of his lectures. I found the book interesting, with some insights that were quite nice, but I think it started a lot better than it ended.

It goes through the history of our species, starting with the origins, going through the changes that shaped our society and identity. It goes on to explain, for example, how almost everything our society is based on is a myth that we collectively cling to and give power to. And he is not talking about religious myths only, but also notions like country, nation, race, money, law, human rights, justice, individuality, good, bad, etc. Like a house of cards, once we started to be able to think abstractly and communicate ideas, we've created a world that is based on assumptions on top of assumptions that we just choose to believe. I thought that was the most interesting point in the book and the one that made me think most. If our entire life as a species and as individuals is axiomatic, then how different could lives be if only based on other axioms?

Another great insight was that liberalism and individuality, coupled with the capitalist growth model that is based on a scientific and technological trust in a better future, are very recent inventions. Most of human history, even up to the nineteenth century, people were content with the status quo, were nostalgic about some bygone era that was "golden" and better than today, and people were stuck into their lives with no hope or even thought of changing them. The explosion of new discoveries and conquests comes from a new found hope in a better future, one based on technological progress and scientific discovery. Other ways of living weren't worse, they just were obliterated by people who chose to accept that they don't know everything and started looking for resources to plunder and answers to their questions. In contrast, whole societies and empires based on the holiness of stations manned by people who assumed knew everything stagnated for centuries.

Yet another point that I found interesting was about the state and commercial institutions eroding and replacing the traditional. Before the legal, moral, support, educational and emotional systems were part of the family or the extended community. Now they are outsourced to law, financial institutions, psychologists, schools, which thrive on the concept that we are individuals and need no one.

Harari makes the point that we are the product of evolution, not different from any other animal, but once we went over a threshold, we created new arenas in which to evolve. Something I didn't particularly agree with is his view that hunter gatherers were living a better, more content life, than farmers. Rather than working all day for a very limited diet, they were free to roam and enjoy the seasonal food that was literally hanging around. Further on we went through the Industrial Revolution and people were even more restricted by the rules of technology and industry. A big portion of the book is dedicated to this kind of thoughts about how our success bound us to a way of life we now cannot escape. The author even uses the word "trap".

In the end, Sapiens tries to analyse our state: is it better now than before? It goes through chapters that talk about happiness: what is it? do we have it? does it matter? Harari is probably agnostic, but he does favor Buddhist ideas of meditation and escaping misery by removing craving, and that is pretty obvious by the end of the book.The last chapter contains a short and kind of reused discussion about the future of us as gods that remake the very fabric of our bodies, minds and reality and, of course, the singularity. But while at the beginning each historical step of Homo Sapiens was analysed with scientific attention, with insights that were clearly coming from a lot of thought on the subject, by the end the rhetoric devolved into just expressing opinions.

So, I did like the book. It felt a bit too verbose, because Harari's style is to explain something, then give an example to make it clearer. If you understand what he explained, the example feels superfluous most of the time. I also didn't like that the book started great, with careful analysis and beautiful insights, and ended with obvious personal opinions superficially backed by facts. I could have accepted either one, but having both just highlights the contrast between them.

As a final thought, Harari mentioned Jared Diamond's Guns, Germs, and Steel (1997) as one of the greatest inspirations for the book by showing that it was possible to "ask very big questions and answer them scientifically". I tried reading that and it was way too thorough and heavy. So having something like Sapiens is like light reading for people who are interesting in science but not very bright :)

Sunday, 12 August 2018

Do NOT Use auto property

So I was writing this class and I was frustrated with the time it took to complete an operation compared to another class that I wanted to replace. Anyway, I am using Visual Studio 2017 and I get this very nice grayed out font on one of my fields and a nice suggestion complete with an automatic fix for it: "Use auto property". Why should I? Because I have a Count property that wraps a _count field and simply using the property is clearer and with less lines of code. It makes sense, right?

However, let's remember the context here: I was going for performance. So when I did ten million operations with Count++ it took 11 seconds, but when I did ten million operations with _count++ it took only 9 seconds. That's a staggering 20% increase in used resources for wrapping one field into a property.

Tuesday, 7 August 2018

A Darker Shade of Magic (Shades of Magic #1), by Victoria Schwab

book cover The idea is nice: multiple versions of the same city of London, somehow named the same, even when the countries and the languages and the magic is different from world to world. Then there is the magician who can go between worlds and the charismatic female thief who accidentally steals from him exactly in the moment of a great change in the structure of power between these worlds.

While I liked the idea and even enjoyed the characters, I felt like Victoria Schwab was more in love with the story than with the characters. Barely sketched, they do things because they do things, not because of an inner drive that makes a lot of sense for them. Even the villains are standard psychopaths doing bad things because they like doing bad things. Plus they kind of suck. I liked A Darker Shade of Magic, I think I may read the rest of the series, but I barely managed to feel anything for the characters. Whenever something needed to happen, some prop or person appeared right then and there. Everybody had stunted emotions that only seemed to push people to action when the plot required it, rather than as a natural consequence of feeling something and plot holes were a plenty.

The bottom line is that I can't recommend this book to anyone, even if I enjoyed reading it.

Friday, 3 August 2018

Facebook are asses and IFTTT messed up, so there might be some issues with my blog posts on Facebook

On the 3rd of August I get this email from IFTTT, a service I have been using to automatically post Blogger posts to Facebook: Hello siderite,

Facebook has recently made significant changes to their platform. One of those changes includes removing the ability for third party applications, like IFTTT, to publish status messages, link posts, and photos on your behalf to your personal Facebook profile.

The following three Facebook actions will be removed from IFTTT starting today, along with any Applets that used them:
  • Create a status message
  • Create a link post
  • Upload a photo from URL

While it’s unfortunate to see some of your favorite Applets removed, we support Facebook’s decisions to evolve their platform in the way they best see fit.

Thank you for your understanding.
The IFTTT Team


It was nice that at least they warned me, but how can anyone imagine that the best way to announce breaking changes in your clients' systems is to write an email that says "from this very second we are going to rip it all away from you"? Even funnier, they link to this Facebook policy change link that was published on April 24th and which announces their own breaking changes starting from the 1st of August. See, IFTTT? This is how you warn your customers: three months in advance.

Strangely enough, some of the applets work, while some just disappeared. I don't mean disabled, I mean completely gone, with no trace or warning on what they had been. Probably these will soon be gone as well. So expect (from this very second) that blog posts will not appear regularly on Facebook until I fix the problem with my own tool. On the other hand, you can always subscribe to the blog itself via RSS, a well proven technology ever since 1999 (that's the reason they partied then). You know that something is good quality when engineers name it: the first letter of its acronym comes from another acronym and when you don't understand what it means even if you have all the words.

Imagine Me Gone by Adam Haslett

book cover Imagine Me Gone is one of those books that I thought I should read because it received prizes for great writing. Maybe I'm too stupid to understand why something that doesn't say anything in the first 5% of it is a good book. The subject is great, too: a family of five people that each describe their lives while battling crippling depression.

I think Adam Haslett found a good way to convey depression: talk endlessly about random pointless things, describe the weather, the way light bounces off of things no one cares about, don't actually express anything or mention anything interesting and occasionally say something really heavy or personally relevant with the same boring and bored rhythm and style. It makes sense, it's the way people feel when in the thralls of this terrible affliction: nothing matters, nothing stands out, it's all grey and pointless. However, a good book means more than just making the reader feel suicidal, it has to have some story to care about, some characters that stand out, anything than just forcing the reader to fight throwing away the book in boredom.

That is why I couldn't even begin to finish the book. I wasn't interested in the depressed description of someone I couldn't care less about, talking about how she handles the depression of others. I can only assume that the high marks for the book are coming either from writing that went completely over my head or from people who were affected by mental illness in the family and read about themselves and got the book. My family is not without its share of psychological problems, but I've had just about enough of it as it is.

Wednesday, 1 August 2018

Revenger (Revenger #1), by Alastair Reynolds

book cover I've read some books in Alastair Reynolds' Revelation series and I more or less liked them. So when I've heard of a new book from the same author I've decided to try it. The result is mixed. For most of Revenger I disliked the characters and the story, but the ideas in it made me want to see what was going to happen next.

What you need to understand is that this is a straight pirate story, only set in the future and in space. It starts with two girls that decide to leave their world and join a spaceship crew in order to make some money. Only they get jumped by pirates, so one of the girls must fight the system and her own nature to become hard enough to find the pirates and save her sister.

The problem is that the characters are hard to empathize with, are pretty inconsistent and always stretch belief in this world in which space crews are uneducated louts speaking in jargon and going from world to world in search for ancient technology they cannot understand that was left by long gone alien races. The only part of the book that made me want to read the next one was the very end, the rest was people acting weird, not thinking too much and speaking a lot.

Bottom line: I can't recommend the book. I might read the next one, after all the books in Revelation Space had wildly varying degrees of quality. The ideas are nice, the implementation is what hurts the book.