EF Code First Notes

I just wanted to make a couple of further notes about EF Code First that I’ve discovered since I started using it:

  1. Cascading Deletes: I don’t like cascading deletes – I prefer notification that linked resources must be removed before a resource can be removed. I find it’s too easy to end up deleting things you don’t want to with Cascading deletes on. To disable this behavior by default, you have to update the ModelBuilder’s conventions in your DbContext class like so:
    public partial class MyContext: DbContext
    {
       static MyContext()
       {
           Database.SetInitializer<MyContext>(null);
       }
    
       public MyContext() : base("MyConnectionString")
       {
       }
    
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
           modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
           modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
           //Configurations go here
       }
    }

    Note that after you do this, your next Add-Migration will result in EF attempting to drop and add all of your Foreign Key constraints. Since I migrated my code base to EF code first from model first, my database already had cascading deletes disabled for existing tables. Therefore, I just deleted the Add/Drop Foreign Key code from my migration code

  2. Creating integer primary key columns that aren’t identities: This one is pretty simple, but when mapping your entities, you must do the following:
    this.Property(t => t.Id)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
  3. Unique Indexes – By default, there isn’t a method on PrimitivePropertyConfiguration that allows unique indexes to be created. I found a great solution on StackOverflow that creates an Extension method that will allow you to create unique indexes.

     

That Conference – Day 2

My second day at That Conference began with a Keynote delivered by Zach Supalla, CEO of Particle, a startup that has created an Internet of Things (IoT) cloud platform. I’ll be honest, when I saw the speaker information ahead of the conference, I wasn’t sure I was going to be interested in hearing another startup story, but I’m really glad I got a chance to hear him speak. I really liked how his first attempt at a consumer product (an adapter for existing lightbulbs that allowed for wifi connection and thus electonic control from other devices) was created as a solution to his father’s hearing loss. The idea was that the lightbulb would flicker when his father’s cellphone rang, alerting him that a call was incoming. While his landline phone used to do this because the house was wired to support this, the cellphone had no such connection. All in all, I really liked the products that his company has produced and the story was pretty inspirational. Even though this product didn’t succeed, they were able to pivot and find an even larger impact with their IoT platform. Zach’s core messages of learning to perservere in the face of adversity and truly listening to their customers was very inspirational – with the right idea, team, and luck, anyone can succeed.

After the keynote, I kicked around the idea of attending several sessions. There were a lot of interesting ones, but I decided to check out the Open Spaces and talked about becoming a Microsoft MVP. I have never really been sure how people got to be Microsoft MVPs, but the process seems pretty simple: put together a strong body of work by demonstrating a passion for your work and the overall impact in your area of focus. After completing an application, your nomination will be reviewed.

At lunchtime, I went to a presentation given by Inrule about their software that allows businesses to define vocabulary and business rules that remove a dependency on hard-coding rules. The core problem their solution addressed was communication failures between the use cases and user stories that business personnel use compared to the developer implementations. Why have a developer interpret the rules when someone who is actually using the software can define the rules themselves. The presentation was really well done, as they used a Star Wars metophor to demonstrate the problems that changing business rules can introduce (particularly when businesses have sizeable amounts of red tape to cut through in order to implement a change).

For the 1:00 session, I attended a discussion called C#: You don’t know jack by George Heeres. There were a lot of useful tidbits involved in the discussion – some of which I was aware with others being new to me. A lot of the things he presented were things I had learned at one point or another but had forgotten due to lack of use. There was a discussion of string allocation and memory consumption and use of IFormatProvider/ICustomFormatter to allow POCOs to have custom String.Format options. One of the most interesting ideas were the ways to create attributes for enums by using extensions methods on the classes that consume the Enums. These attributes allow you to provide an English readable name for each enum. There was some discussion at the end about returning IEnumerable collections on models from the database instead of IList or List because IList has methods that imply functionality that may not be there (add, update, remove). The argument was that those terms mean add/update/remove to a data store, although I see them as valid because you are modifying the collection regardless of whether that collection is in memory or part of a datastore. Context about where you are using the collection is important.

The 2:30 session wasn’t one of my favorites. It had to do with starting out with IoT, but the presentation was very fast-paced with the intent of doing live demos of several objects built by the presenters. Unfortunately, they ran into problems connecting to wifi, both locally and in the cloud, so they ended up spending a lot of time trying to get their connection working. I am not sure whether they ended up getting everything to work because I left to check out the Open Spaces. Earlier in the day, I had met Maggie Pint, a Microsoft software engineer who also maintains the excellent moment.js library, and she told me about her talk going on at 1:00 and Open Spaces session at 2:30. It was clear after talking with her for just a couple of minutes that she was an expert in her topic regarding the complexities of date and time (anyone who has spent any time thinking about date and time across time zones knows how complicated this topic really is). I caught a little bit of the discussion at her 2:30 open space discussion, but not as much as I would have liked. In retrospect, I really wish I would have been able to attend two 1:00 sessions.

My last session for the day was about domain-driven data, given by Bradley Holt. It was a thought-provoking session that related strongly to Eric Evans 2003 book Domain Driven Design, which I partially read some years ago, and recall being very influential. After the discussion, I think I need to re-read some parts because a lot of the concepts are still relevant to today’s industry. I’ll admit that I haven’t had to think much about my data store – I have mostly worked with low-scale websites, so a relational database has always been the defacto choice for me. However, a strong case was made for a model which leverages the strengths of different persistence strategies: Key-Value stores, document-driven databases, graph databases, relational database models, and some others. One of the most interesting things about the discussion was in the discussion of Aggregate Roots (a DDD concept from the aforementioned book). In the strictest sense, aggregates that are not the root should not also be an aggregate root in another scenario. Consider the following object:

public class Order : IAggregateRoot
{
    public int Id { get; set; }
    public int CompanyId { get; set; }

    public virtual Company Company { get; set; }
}

In this case, the Company object is an aggregate, but not an aggregate root. Therefore, the Company object should not be an Aggregate Root of its own. One solution proposed by another attendee was to have an “OrderCompany” object that had foreign key constraints to the Order and Company table. This way, Company can still exist as an aggregate root, and so can Order. These kinds of sessions are my favorite because they really make me think about architecture, one of my favorite things.

That Conference – Day 1 (Mostly)

This week, I’m at That Conference in Wisconsin Dells, WI. It’s a 3-day, language agnostic developer conference, and I have attended for the past four years (this year inclusive).

That Conference logo

I actually started on Saturday and Sunday by participating in Give Camp, which is essentially a hack-a-thon. This year, as last year, the project to which we contributed is Humanitarian Toolbox, which aims to work provide software to prevent, prepare for, and respond to disasters. Working on Humanitarian Toolbox was my first exposure to open source projects, and I really felt like I was able to contribute on the project well this year. Not only did it give me an opportunity to work with other people (an opportunity that I relish since I work as a solo developer at my day job), but I also gained some exposure to some new technologies (.Net Core, Git, MoQ, etc). I look forward to continuing to contribute with the project and watch it mature into something that can really help people.

Today was the first day of regular sessions. The keynote, titled “You have too much time”, was delivered by Jeff Blankenberg and focused on the idea that people are generally very bad at prioritizing their time. We use excuses such as “I don’t have the time” or “I am too busy”, but we really mean “I did not prioritize this” or “I would rather be doing something else.” When examining waking hours, time spent consuming media alone is often more than an entire month of the year. However, I think it’s important to note (as did the speaker) that time spent consuming media where you have specifically chosen that as your priority is perfectly acceptable. For the most part, I feel good about where I am right now, but I have spent a lot of time thinking about this problem. Earlier this year, I implemented a Kanban system at home to try and help me prioritize the projects and things going on in my life. My work Kanban has been a lot more successful than my home life board, though, as some tasks just languish and never seem to see completion.

The first session I attended was a discussion on microservices lead by Mark Heckler. I am a sucker for discussions on architecture and new ideas in software engineering, and microservices seems to be the direction that most things are headed. Mark had a really great analogy to describe the differences between SOA (service-oriented architecture) and microservices: SOA tends to be more like an orchestra where a conductor leads the group, whereas microservices are more like having a choreographer teach the group the moves.

Having written monolithic applications and also watching the .Net framework become a monstrous, resource-intensive thing over the years, I have seen firsthand the issues that can arise from this approach. So has Microsoft, obviously, as they have really embraced modularity with their approach to .Net Core and the future of their framework. One of the things that hit home the most for me about monoliths is that failure in a single component leads to failure of the whole, and a fix requires replacing the entire executable. Making a change in a large, monolithic structure can also be daunting if you aren’t familiar with the architecture – I remember that it took me somewhere around six months to get my head around the main application when I started working at my current job. This is definitely a topic I want to explore some more and see how I can take advantage of what microservices can do for the applications I develoop. One of the resources offered was a site called 12factor.net which details a methodology for building software-as-a-service apps.

The second session I attended was about continuous security, and offered some ideas for integrating security tools into build and/or continuous delivery pipelines. Security is something I have spent a lot of time reviewing over the past year or so, but Wendy Istvanick’s talk taught me a lot of things I could and should be doing to really make sure that my software is being checked for vulnerabilities. One of the highlights was the use of OWASP (Open Web Application Security Project) to identify project dependencies with known vulnerabilities. Like any good developer, I include a variety of third-party packages in my project, and they usually have their own dependencies that I don’t even think twice about. Being able to view a report of which dependencies might have known vulnerabilities is a big plus. Another tool called talisman is a precommit hook that prevents team members from checking in sensitive information (passwords, app secrets, etc). Finally, OWASP Zap sends out attacks to whereever you point it, and there are ways to automate this (in addition to providing a web interface).

Kirsten Hunter gave the third presentation of the day, and it was about becoming a polyglot (or, one who is comfortable programming in multiple, disparate languages). I’ve always liked the idea of dabbling in many different languages, but have had trouble overcoming the issues of setting up the infrastructure to get everything working. The speaker at this session had set up a docker container that had the code to stand up instances of essentially the same API (a random quote generator) in five different languages: python, ruby, php, perl, and javascript. I plan on using this as a starting point to examine other languages and commit new languages back to the project after I’ve had a chance to become familiar with the project.

Lastly, I went to a session on optimizing Asp.Net core code to be more SOLID (single responsibility, open for extension/closed for modification, liskov substitution, interface segregation, and dependency inversion). The session was given by Jimmy Bogard, who wrote the excellent AutoMapper, a tool that I use every day to map my domain entities to view models. Asp.Net core has given the ability to write more flexible IActionFilters that plug in to the services configuration section of Startup.cs than previous versions. This now allows us to remove a lot of duplicative code, especially in things like POST requests that follow a similar pattern: validate input, map to database entity, persist to database. He also detailed some of the abilities of AutoMapper to project specific columns directly from the database without having to hydrate the entities into memory first. Finally, he gave some good reasons for more clearly defining the transaction scope that Entity Framework uses – it’s not always clear what the scope is when you call “Save changes” in your code.

His examples also made me think about using a flatter structure of my code. I use a pattern that requires several layers and the repository / unit of work patterns in concert, but as frameworks develop, it seems that much of this is unnecessary and adds some overhead. For one thing, I am unable to take advantage of the ProjectTo optimization because I am hydrating my entities in a service layer and passing them back to my controllers.

Overall, I really enjoyed the first day and am looking forward to the second.