Simple.Data, how to select when column name contains ?, -, / and other special character? - simple.data

I am using Simple.Data to query the DB. but this particular DB is imported from Access DB.
some of the filed names has space, -, / in it.
Policy Number
FTZ?
Prod/Co
Covg - Years
is it possible to use Simple.Data? how do you name your object so Simple.Data will know which field to query.
public class item {
public string "Policy Number" {get; set;}
public string "FTZ?" {get; set;}
...
}

You can just leave out non-alphanumeric characters in your identifiers, and Simple.Data will still find the matching columns.
e.g.
Item item = db.Items.FindByPolicyNumber(pnum);

Related

ServiceStack ORMLite - Select columns

I recently started working with ServiceStack and its ORMLite framework. I have searched on Google and browsed the source code but couldn't find anything relevent.
Is there any way to select specific columns when executing a query with ORMLite ?
Something like that : Db.First<Model>(q => q.Id == someId, "Column1, Column2")
Unless I missed this feature, I am surprised nobody asked about this before, since this is one the rule of thumbs to optimize your DB transactions.
If you want to specify columns other that the table you need to use SQL as seen in this earlier example
So in your case you could do something like:
Db.First<Model>("SELECT Column1, Column2 FROM AnyTableOrView");
You can also create a partial model that looks at your table by decorating it with the [Alias] attribute, like:
[Alias("AnyTableOrView")]
public class Model {
public int Id { get; set; }
public string Column1 { get; set; }
public string Column2 { get; set; }
}
Then you can do something like:
Db.First<Model>(q => q.Id == someId);
And it will only SELECT + populate fields from the partial model.
I did try this :
Created a Database VIEW (table name and columns are already set)
Created a class named "Event" and matching each fields for that table with a property
(i used [Alias] for table name and for all columns to have nice names)
Wrote access to DB to select 1 record based on it's ID
var dbFactory = new OrmLiteConnectionFactory(
"Data Source=MyDB;User Id=user;Password=pwd", // Connection String
OracleDialect.Provider);
using (var db = dbFactory.OpenDbConnection())
{
var event = db.GetByIdOrDefault<Event>( request.Id );
}
At that point the var 'event' is populated but only the Id field is filled !
all the others fields of the class are not filled (while there are really data in database).
It's the simplest i can do and it does not work. Any ideas ?
(PS : i am using OrmLite for Oracle)
Thanks
I have found the problem.
It was due to an incorrect type matching between field in my class (defined as a string) and the corresponding Oracle Field (that is a DATE).
I replaced the string with datetime and worked like a charm.
So it's working perfectly with a VIEW and that's GREATLY simplify the code.
I had a similar problem, however my solution was different.
I had a int property in my POCO. My query (from Oracle) was returning a null for this property. It caused a exception to be raised and prevented further processing of that row.
The result was a partial populated POCO.
The solution was to change to type to be nullable.
public int? mypropperty

How do I query navigation properites using linq to sql and ef

I am trying to strongly type a query for 3 ef objects using linq to sql. There are one-to-many relationships with product and category. My classes contain navigation properties and look like this.
public partial class Product
{
public int ID {get;set;}
public string Name {get;set;}
public virtual ICollection<Group> NpGroup {get;set;}
}
public partial class Category
{
public int ID {get;set;}
public string Name {get;set;}
public virtual ICollection<Group> NpGroup {get;set;}
}
public partial class Group
{
public int ID {get;set;}
public int ProductID {get;set;}
public int CategoryID {get;set;}
public virtual Product NpProduct {get;set;}
public virtual Category NpCategory {get;set;}
}
Trying to avoid the string based .Include(), how would I construct a query that returned a group equal to ProductID "1" but also included the names of the product and category?
Something like:
var context = ObjectContext.CurrentObjectContext;
var query = from c in context.Group
where c.ProductID == 1
//Include the names of the product and category of the group record (c.NpProduct.Name etc.)
select c;
I am probably missing the trees through the forest but I can not seem to get the syntax of ObjectContext.LoadProperty (if that is the right way to go).
Any thoughts? Thanks.
First of all, i doubt you are using both L2SQL and EF, so try not to confuse people.
Anyways, with EF - there is two ways to load the navigational properties:
1 - Eager Loading
q.Include("NavPropertyName")
2 - Explicit Load
*After* running your above query - use q.NavPropertyName.Load()
Difference is option 2) causes 2 queries, option 1 causes an inner join on the FK.
I can sympathise with your reluctance to use Include because of the 'magic strings' - i'm not sure why the EF team didn't make them strongly typed, however im sure there was a good reason.
More info on Load/Include here.
HTH
I think we all hate to use the typed string in the .include() statement.
I've started to use a enum to represent the table name, just to avoid spelling errors, etc.
for my database of about 70 tables it took me 10 min. to create the enum and my linq is now something like this:
var context = ObjectContext.CurrentObjectContext;
var query = from c in context.Group.Include(TableEnum.Category.ToString())
where c.ProductID == 1
select c;
Again, not perfect, but at least it's checked by the compiler

MVC 2 Model Validation messages

i have a view model with a property like this one :
[RegularExpression(#"^d\+$", ErrorMessageResourceType = typeof(Resources.Validation), ErrorMessageResourceName = "NumberValidationMsg" )]
public int? Number {get; set;}
NumberValidationMsg resource is set to "Only numbers allowed !".
but when I try to enter something like 'test' into Number field on form, ModelState displays the ErrorMessage with content similar to : "The value 'test' is not valid for Number."
can this message be turned off, customized ?
(or maybe the best solution would be just to replace int? with string )
Thank You !
If you want to accept text in the field, you need to change it to a string, and make your conversions to int according to your rules.
If your model is an int, then the only valid input will be int (or empty, if it is "int?"), and you should not try to prevent this unless there are good reasons... Moreover, I believe that you could leave the whole regular expression out, because the MVC already does that check for you implicitly (because it is an int).

How to set minOccurs to 1

I'm building an ASP.NET web service.
I've got my code defined as below, but I can't figure out how to the the wsdl to specify the minOccurs of the FirstName and LastName properties. I want those as required, and can not be empty. Is it possible?
[WebMethod()]
public void TestMethod(TestClass Test)
{
...
}
[Serializable]
public class TestClass
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
It turns out that the WSDL is not used to validate incoming XML. It wouldn't matter whether or not you could specify minOccurs - it would not be used to validate the input.
I have posted the detailed answer on another thread with the same problem: How to make a dotnet webservice set minOccurs=“1” on a string value.
However the answer for strings is no.
The only way make minOccurs=1 without nullable=true is to declare a property with no default value (string has a default value of String.Empty) and without a property to check if the value was specified (making an identical property name with "Specified" word appended to it's name).
And you are still limited if John Saunders' answer is true.
It turns out that the WSDL is not used to validate incoming XML. It wouldn't matter whether or not you could specify minOccurs - it would not be used to validate the input.
Strings are reference types and so by definition nullable. If your property was an integer minoccurs would have been 1.
You can force the Serializer not to allow it to be null, by putting.
[XmlElement("name", IsNullable=false)]
above the property.
Edit: I meant reference types instead of value types. Thnx Joren!

ASP.NET which type of collection should I use?

I am writing a class to save searches on my site. I want to have in the class an "Array" of all the parameters that were specified. I tried a NameValueCollection but the problem I ran into is when I have a multi-select (e.g. states) it only stores one of the entries because the key gets taken. I need a collection type that will let me have something like the following:
Name => Bob
State => Alaska
State => Oregon
State => Washington
Company => Acme
What type of collection should I use?
EDIT: ==============================
I'm not sure the comments so far will help. Let me explain a little further. This search class will be used to save the parameters for any search on my site. Different searches may or may not have the same parameters. When this classes save method is called the search will be dumped into a database. One record will be created in the Searches table and as many records an there are items in the collection will be created in the SearchesParameters table. The SearchesParamaters table has these columns (ID,searches_ID,key,value).
The database could care less if there are two parameters with a key of "State". In order to keep my class generic enough to use on all searches without having to be updated I want to have a collection/array that will let me have key/value pairs and also let me have multiple instances of the same key. Really I just want to be able to call searchObj.addParameter(KEY,VALUE); How the class handles that on the back end is mostly irrelevant so long as i can reliably get the correct keys paired up with the correct values.
Is a collection the way to go with this or should I be considering something like two arrays one storing the keys and one storing the values?
A Dictionary that maps String to an List<string>. Something like Dictionary<string, List<string>>.
If an element isn't there in the Dictionary, create a new List for the Key and add to it. Otherwise, simply add the new Value to the existing List.
Create a class, and store that class in a collection.
class Search
{
public string Name { get; set; }
public List<string> State { get; set; }
public string Company { get; set; }
}
Then you can have multiple states per search. Add instances of this to List and away you to.
what about a generic list (System.Collections.Generic)?
e.g.,
string name;
List<string> states;
string company;
You can read up about generic lists here
You should use a List<KeyValuePair<string, string>>
I would use Dictionary<string, HashSet<string>>.

Resources