.Net Core Fluent API with Nullable references types - ef-fluent-api

I can't seem to solve the following problem and can't find anything online that helps. I'm new to .Net Core and am also new to using nullable reference types and somehow I can't make them work together with EF Core. I have a data table that includes a One to Many relationship where the foreign key is nullable (i.e. it's possible that there are no items in the relationship - in this example not all Assets have AssetTypes). The fluent API which used to work was
modelBuilder.Entity<Asset>(entity =>
{
entity.HasOne(d => d.AssetType)
.WithMany(p => p.Assets)
.HasForeignKey(d => d.AssetTypeId)
.HasConstraintName("FK_Assets_AssetTypes");}
The problem is since AssetType? is nullable I'm now getting a
'p' may be null here...warning on p.Assets
and can't seem to find a way around it short of suppressing the message and hoping it works, which it seems to although other Many to Many relationships do not and need to be dealt with manually. EFCore appears to be quite primitive on Many to Many unless I'm doing it wrong.
I have tried reversing the relationship by starting with the AssetType entity but I get a similar result.
I've also tried using
.WithMany()
but this removes an existing navigation property and so it doesn't work.
Any help would be appreciated as I'm obviously missing something.

I just encountered similar situation when configuring mapping expression. In the end, I decided to silence the warning, because the expression as written is never executed. It is only parsed by EF to do it's internal magic. In your case it would be like this (no need to deal with #pragma warning disable)
modelBuilder.Entity<Asset>(entity =>
{
entity.HasOne(d => d.AssetType)
.WithMany(p => p.Assets!)
// ^ this '!' tells to compiler to stop bothering you about this
// null dereference because you are sure the code is right
.HasForeignKey(d => d.AssetTypeId)
.HasConstraintName("FK_Assets_AssetTypes");
}

Related

RSpec: Problems converting to the new "allow" syntax for mocks/stubs

I am trying to learn rspec and apply what I am learning to an existing rails app.
I am trying to create a mock of a user called "current_user"
I have basically taken this line of code
controller.stub(:current_user).and_return(build_stubbed(:user))
and placed it before my tests (all of which require a current_user to be defined)
This works. But
I know that this syntax is deprecated and I should be using
allow().to receive().and_return()
syntax but I can't seem to convert it to the new syntax and get it to work.
I tried
user = double("user")
allow(user).to receive(:current_user).and_return(build_stubbed(:user))
without success. I reality I have no idea what I am doing with this and need to be pointed in the right direction. I have looked extensively for an answer but I suspect this is too basic.
Would appreciate some guidance.
Currently, you're stubbing the current_user method for your controller variable. In your new syntax example, you've put the stub on the user double object.
Without knowing more about build_stubbed, I would expect it to look like:
allow(controller).to receive(:current_user).and_return build_stubbed(:user)

Mongoid 4 finding embedded documents by ID

I have a project that is my first serious dive into Mongoid.
I saw a tip to use the following command:
Parent.where('childrens._id' => Moped::BSON::ObjectId(params[:id])).first
But this doesn't work. Error message was:
NameError: uninitialized constant Moped::BSON
I found that BSON is no longer included, so I added it to my Gemfile, as well as Moped. Then, I did another fix I found (placing Moped::BSON=BSON in application.rb).
This still didn't work, but the error changed to:
NoMethodError: undefined method `ObjectId' for BSON:Module
So I am assuming that this method got deprecated or something. Does anyone have any other tips?
Just to be clear, I am finding myself in the situation where I want to sort embedded documents using jquery-sortable. This requires me to update them in the database, but the serialize from that doesn't include the parent document in the hash. So I figured I'd try to get it on the back end using an ID from the embedded document. That is why I need it.
Thanks again for any help you can provide.
Try simply:
Parent.where('childrens._id' => params[:id]).first
I have solved the question though this won't be of much help to people in the future. The requirements have changed and now I am using human-readable strings as IDs to assist in friendly URLs and some other stuff.
Therefore, I don't have any issues with ObjectIds. Cortex's solution should (from what I have read) work for dealing with ObjectIds but I cannot verify it now.

RESTful API and Foreign key handling for POSTs and PUTs

I'm helping develop a new API for an existing database.
I'm using Python 2.7.3, Django 1.5 and the django-rest-framework 2.2.4 with PostgreSQL 9.1
I need/want good documentation for the API, but I'm shorthanded and I hate writing/maintaining documentation (one of my many flaws).
I need to allow consumers of the API to add new "POS" (points of sale) locations. In the Postgres database, there is a foreign key from pos to pos_location_type. So, here is a simplified table structure.
pos_location_type(
id serial,
description text not null
);
pos(
id serial,
pos_name text not null,
pos_location_type_id int not null references pos_location_type(id)
);
So, to allow them to POST a new pos, they will need to give me a "pos_name" an a valid pos_location_type. So, I've been reading about this stuff all weekend. Lots of debates out there.
How is my API consumers going to know what a pos_location_type is? Or what value to pass here?
It seems like I need to tell them where to get a valid list of pos_locations. Something like:
GET /pos_location/
As a quick note, examples of pos_location_type descriptions might be: ('school', 'park', 'office').
I really like the "Browseability" of of the Django REST Framework, but, it doesn't seem to address this type of thing, and I actually had a very nice chat on IRC with Tom Christie earlier today, and he didn't really have an answer on what to do here (or maybe I never made my question clear).
I've looked at Swagger, and that's a very cool/interesting project, but take a look at their "pet" resource on their demo here. Notice it is pretty similar to what I need to do. To add a new pet, you need to pass a category, which they define as class Category(id: long, name: string). How is the consumer suppose to know what to pass here? What's a valid id? or name?
In Django rest framework, I can define/override what is returned in the OPTION call. I guess I could come up with my own little "system" here and return some information like:
pos-location-url: '/pos_location/'
in the generic form, it would be: {resource}-url: '/path/to/resource_list'
and that would sort of work for the documentation side, but I'm not sure if that's really a nice solution programmatically. What if I change the resources location. That would mean that my consumers would need to programmatically make and OPTIONS call for the resource to figure out all of the relations. Maybe not a bad thing, but feels like a little weird.
So, how do people handle this kind of thing?
Final notes: I get the fact that I don't really want a "leaking" abstaction here and have my database peaking thru the API layer, but the fact remains that there is a foreign_key constraint on this existing database and any insert that doesn't have a valid pos_location_type_id is raising an error.
Also, I'm not trying to open up the URI vs. ID debate. Whether the user has to use the pos_location_type_id int value or a URI doesn't matter for this discussion. In either case, they have no idea what to send me.
I've worked with this kind of stuff in the past. I think there is two ways of approaching this problem, the first you already said it, allow an endpoint for users of the API to know what is the id-like value of the pos_location_type. Many API's do this because a person developing from your API is gonna have to read your documentation and will know where to get the pos_location_type values from. End-users should not worry about this, because they will have an interface showing probably a dropdown list of text values.
On the other hand, the way I've also worked this, not very RESTful-like. Let's suppose you have a location in New York, and the POST could be something like:
POST /pos/new_york/
You can handle /pos/(location_name)/ by normalizing the text, then just search on the database for the value or some similarity, if place does not exist then you just create a new one. That in case users can add new places, if not, then the user would have to know what fixed places exist, which again is the first situation we are in.
that way you can avoid pos_location_type in the request data, you could programatically map it to a valid ID.

Ember camelize() vs javaScript camelize()

I'm trying to camelize an extracted value from an ember view, and I was hoping to get the lower case camelized form of a string as is written here http://docs.emberjs.com/symbols/Ember.String.html#.camelize
However, what I'm getting back is the capitalized version of it (the extracted value started off as Capitalized).
Try this Ember.String.camelize("my lovely property") which gives you myLovelyProperty
I can confirm that My-Lovely-Property isn't converted to myLovelyProperty. Nor is MY-LOVELY-PROPERTY -- it leaves those "OVELY" "ROPERTY" caps alone too and yields MYLOVELYPROPERTY which certainly doesn't feel like camel case. I'm not sure if that behavior is intended or not, but it seems neither this case nor yours is covered by the test examples.
If you or anyone else believes strongly that such cases should be covered in some way, perhaps submit a github issue or PR? Otherwise, for the case you describe you can use an expression like str.charAt(0).toLowerCase() + str.substr(1).camelize().

Is there any cleaner way to do this? (Prepared SQL queries in Qt C++)

I'm using QSqlQuery::prepare() and ::addBindValue() for my queries in a Qt project I'm working on. There's a lot of repeated code and though I think that's the "right" way, I wanted to make sure. Perhaps someone has alternative ideas? Example:
QSqlQuery newQuery;
newQuery.prepare("INSERT INTO table "
"(foo,bar,baz,"
"herp,derp,biggerp,"
"alpha,beta,gamma,"
"etc) VALUES "
"(?,?,?,"
"?,?,?,"
"?,?,?,"
"?)");
newQuery.addBindValue(this->ui->txtFoo->text());
newQuery.addBindValue(this->ui->txtBar->text());
newQuery.addBindValue(this->ui->txtBaz->text());
newQuery.addBindValue(this->ui->txtHerp->text());
newQuery.addBindValue(this->ui->txtDerp->text());
newQuery.addBindValue(this->ui->txtBiggerp->text());
newQuery.addBindValue(this->ui->txtAlpha->text());
newQuery.addBindValue(this->ui->txtBeta->text());
newQuery.addBindValue(this->ui->txtGamma->itemText(0));
newQuery.addBindValue(this->ui->txtEtc->text());
newQuery.exec();
You can see there's a bunch of the same "newQuery.addBindValue(this->ui->__________" over and over. Is this the 'best' way to go about it?
Also, I asked in #qt on freenode the other night but didn't get a definitive answer; will the above (::prepare with ::addBindValue) protect agains SQL injection? The reference didn't really say.
It might look a bit tidier if you first create a QMap or QStringList with the bindings, then iterate through that data structure and call addBindValue() for each item in the list/map.
In relation to your sub-question on SQL injection, that combination of ::prepare and ::addBindValue does indeed fully protect against it. This is because the bound values are never parsed by the SQL engine; they're just values that slot in after compilation (the preparation step) and before execution.
Of course, you have to be careful when taking values out of the DB too, but that's not protecting the database but rather ensuring that the values aren't used to cause other mischief (e.g., injecting unexpected malicious <script> tags into HTML or, worse still, a <blink> or <marquee> monstrosity). But that's another problem, and doesn't apply to all uses anyway; putting the values in a strictly plain text GUI field is usually no problem.