Entity framework 6 no results - asp.net

Ive just setup entity framework 6 (for first time) using a model with same fields as db table but im getting 0 results on debug (no errors)
public class footballContext : DbContext
{
public DbSet<football> football { get; set; }
}
and:
var context = new footballContext();
var matches = context.football.Take(20).ToList();
If I view the query its using on "context" I can run it on my database and results are returned fine. I do have entity framework power tools but it only seems to validate the model, is there a way I can test if it can get data or is there something obvious I've missed?

Just found this:
"If you don't specify a connection string or the name of one explicitly, Entity Framework assumes that the connection string name is the same as the class name. The default connection string name in this example would then be SchoolContext, the same as what you're specifying explicitly."
Think I need to start reading up on the naming conventions for this...

For your code to work as it stands, you will need to have a connection string in your web.config called footballContext
If you don't want the connection string to be called that you can create a constructor for your context which calls the base constructor with a specified name.
If you prefer to pass in the connection string explicitly during creation of the context you can again create a constructor for footballContext which accepts a connection string and calls the appropriate base constructor.
See this SO answer for an example.

Related

D365FO x++ syscomputedcolumn table name

How can you use the syscomputedcolumn class to retrieve a table or field name for an entity? this is fairly easy using virtual field entity postload method something like
public class SysDatabaseLogHeaderEntity extends common
{
public void postLoad()
{
super();
this.TableName = tableId2Name(this.table);
}
}
but there's a rumour that virtual fields won't be supported in upcoming synapse link for D 365 FnO so want to know how to do this with computed columns...
https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/data-entities/data-entity-computed-columns-virtual-fields
SysComputedColumn is used to help create computed columns in views.
Supposing for some reason you want a column in which every row contains the string value "CustTable", you'd create create a method (AX 2012 syntax):
public static server string TableNameColumn()
{
return SysComputedColumn::returnLiteral(tableStr(CustTable));
}
and then you'd add a computed column to the view as outlined here: https://learn.microsoft.com/en-us/dynamicsax-2012/developer/walkthrough-add-a-computed-column-to-a-view
Note: hopefully this is a toy example, there is no reason to ever actually do this particular column. Or really any fully static columns.
View computed columns are essentially based on static server methods which return the SQL definition for the computed column, and then the SysComputedColumn class has a bunch of helper methods to let you build those SQL string statements without using specific implementation knowledge of the backend database such as column names.
A complete description is beyond the scope of this comment, but the big one you'll use is SysComputedColumn::returnField(view,datasource,field) which gets the specified field from the specified datasource in the specified view. You want to use intrinsic functions for these parameters to keep your cross references valid (https://learn.microsoft.com/en-us/dynamicsax-2012/developer/intrinsic-functions).
There will be a lot you can't do though. These are sql only so they cannot send individual rows into X++ business logic. You need to reconstruct said business logic in SQL which can't always be done easily.
I like to keep those methods public so I can info them out and test them in SQL directly. I'm guessing you can't access the sql in d365, but looking at the string returned from your method can still help in troubleshooting.

Custom Binding Required for SpringMVC Form Field

I ran into the following SpringMVC issue: there is a domain object which uses a certain Address sub-object, but the getters/setters have to be tweaked to use a different Address object via conversion. This is an architectural requirement.
public class DomainObj {
protected DomainObj.Address address;
public anotherpackage.new.Address getAddress()
{
return convertFrom(address);
}
public void setAddress (anotherpackage.new.Address value)
{
this.address = convertTo(value);
}
}
// Internal Address object, old, #1
public static class Address {
protected String street1;
protected String street2;
// etc., getters/setters
}
Now, in the JSP, I bind an Input Text Field to the new Address object (the result of conversions) that's what we have to deal with. In this new 2nd Address object (anotherpackage.new.Address), there is a field e.g. "addressLine1", which is different from the old object's "Street1":
<form:input path="topObject.address.addressLine1" />
My problem is that the setter, setAddress(), never gets called in this case for binding (verified in the Debugger). Any solutions to this?
Your options are:
a) do not bind directly to the business object
b) configure a binder to do the conversion to your domain object
Discussion:
Usually in enterprise class software we don't want to bind directly to the business objects -- which are usually entities (in the context of jpa). This is because session handling is a bee-otch. Usually we code against DTOs, and when one is received from the front-end we read the appropriate object from the repository (ORM) layer, update it, and save it back again (I've only described updates because they're the hardest, but a similar model works for everything).
However, spring mvc binders offer a way of binding anything to anything. They're a bit complicated and it'll take too long to explain here, but the docs are in the spring documentation and you want to be looing at converters and a conversion service. There are SO Q/A's on this topic, for example...

ASP.NET MVC - How to handle a string in a model that does not allow nulls?

So I'm a bit new to ASP.NET and MVC. I've got an ASP.NET MVC5 application, using Entity Framework 6. I've generated my models from a SQL Server database, and am so far just using the vanilla index/create/details/edit constructs.
In my models, various fields are marked as "Allow Nulls" and others aren't. While creating a new entry, any type that is, say, an int that is left as null is handled nicely by the ModelState.IsValid check and the #Html.ValidationMessageFor messages.
On one entry test, however, I received a DbEntityValidationException. I used the try/catch from this question to find out that it was one of the string (VARCHAR) fields that was left blank.
I am assuming this is because the string class allows nulls, where as int does not (unless declared as Nullable<type> in the model) thus the controller/model doesn't flag it as invalid.
What would be the easiest way to handle this? Is there a way to decorate the string property in the model so it gets checked as well? Or do I need to go as far as attempting to save, catching the exception, and manually handling the validation messages?
Thanks
It is possible to decorate your property with a Required-attribute. Mvc wil show an error message when the user is posting a form while this property is empty.
public class TestClassModel
{
[Required]
public string RequiredString { get; set; }
}

Object property validation in MVC (using web service)

I have an ASP.Net MVC site, which connects to a web service.
The site's view model contains objects for each group of required service data AccountDetails (containing AccountId, AccountType, etc.), ContactDetails (containing Name, Address, etc.) and so on.
The service has a 'CreateUser()' method that accepts these objects as parameters, and it then performs all the validation itself - handing back an Object which has an array of any errors that have been found, including the name of the specific property/field.
I would like to know if there is a way of passing this returned error data into either DataAnnotations or something else.
I specifically can't write the conditions in the model itself, because the validation conditions within the web service are open to change at any moment - and we want this to dictate what fails and what succeeds.
== FURTHER INFO FOR MAKE IT A BIT CLEARER ==
Imagine I were locally (within the View Model) creating the ContactDetails class, I could very simply do this
public class ContactDetails
{
[IsRequired()]
[CustomAttributeofSomekind]
public string FirstName { get; set; }
public string LastName { get; set; }
}
However in this scenario - if we wanted to change the validation critera for whatever reason we would have to change it in both the web service AND in all the client websites that access the service.
We don't want to have to do this - instead I if (in the above) scenario ContactDetails.LastName is suddenly required and must be no more than 10 characters - this should only need updating in the web service.
I think you have two options:
Create a User class to wrap the CreateUser() method and add the DataAnnotations to that (this is what I would do, it allows you to go strongly-typed.)
Call the CreateUser() method directly from the controller Action and use server-side validation. Add each validation error in the CreateUser() result to the ModelState.Errors collection when any validation rules are violated.

Is static caching DatabaseFactory.CreateDatabase acceptable?

Is it acceptable to cache an instance of the database connection on application start?
Looking at the MSDN documentation on thread safety, I quote:
Any public static [...] members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Given that, is it acceptable/safe for code such as this example below:
public static class BookingMapper
{
public static Database Db { get; set; }
static BookingMapper()
{
Db = DatabaseFactory.CreateDatabase();
}
public static string GetBooking(int id)
{
using (DbCommand cmd = Db.GetStoredProcCommand("getBooking"))
{
Db.AddInParameter(cmd, "#Id", DbType.Int32, id);
using (IDataReader dr = Db.ExecuteReader(cmd))
{
...
}
}
}
}
If it is acceptable, what are the benefits/drawbacks of using such an approach over simply instantiating the Database on every single method call?
Thanks in advance.
Update:
Further research has pointed me to a PrimaryObjects.com article which, in the Putting the Database Factory to Use section suggests that this is acceptable. But I'm still wondering if there are pros/cons to doing it this way?
Similar question
1) There are two ways to interpret that standard phrase on Thread Safety from MSDN, and I wish they'd clarify it. Your interpretation would be nice, but I believe that what it means is that:
Any members (methods, fields, properties, etc) that are part of this type, and that are public and static, are thread safe
(e.g. there are two ways to interpret the subphrase "members of this type")
2) Generally, you don't want to share a db connection around - you want to open a connection, do your job, and close it. You can't generally have multiple open readers associated with a single connection (this is generic db/connection advice, not ent library specific).
3) On some further reading inside the ent library, the Database object returned by the CreateDatabase call isn't a connection itself, and it looks like the connection management is handled as I stated in point 2. So it looks like the Database object itself can be safely shared around.

Resources