I have a Hospital table and the Addresses tables where i have written a simple data query to the DB
db.Hospitals.All().Join(DB.Address,out address).
Select(db.Hospitals.name,address.PostCode.As(Address.PostCode));
The Hospital Model class has Address internally
Class HospitalModel
{
public string Name{get;set;}
public HospitalAddress Address{get;set;}
}
public class HospitalAddress
{
public string PostCode{get;set;}
}
I am able to get the Name property but the postcode in HospitalAddress doesn't seem to work. Wondering where this is a problem .
Try:
db.Hospitals.All().WithAddress();
That should eager-load the Address which will make the cast work as expected.
Related
I have the following get-method:
public async Task<TModel> Get(string id)
{
var filter = Builders<TModel>.Filter.Eq("_id",id);
var result = await _collection.FindAsync(filter);
return result.FirstOrDefault();
}
My Model is defined like this:
public class Entity
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
...
}
If I test this method I get 404 (Not found) back.
What I already checked:
The id parameter has the right id.
Used id exists in database.
_collection is the correct IMongoCollection.
MongoDB server is running and collection exits.
Connection string, credentials and permissions to connect to the MongoDB server is correct (other crud methods are working).
What other troubleshooting steps can I do? What could be the error?
Thank you for your help!
In the Entity class the _id field is defined to be ObjectId, but in the Get function it is string. MongoDB matches are type-sensitive, so you'll need to convert the string to an ObjectId first.
I'm using OrmLite with both SqlServer, Oracle and PostgreSQL dialects.
I want to use GUIDs as primary keys and have a simple object, using the AutoId attribute:
public class MyObject
{
[AutoId]
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
...
All goes well with SqlServer and PostgreSQL dialetcs, but with Oracle I get an initial GUID with all zeros in the db, and a subsequent INSERT violates the unique key constraint of my primary key. How can this be accomplished db agnostic so it also works with Oracle?
Based on the source code I'm looking at, it doesn't appear to properly generate GUIDs for anything that's not SQL Server or PostgreSQL, regardless of what the documentation actually says on the README. Relevant code links below:
SQL Server
PostgreSQL
Base Dialect Provider
The best alternative I can provide here is to override the OracleOrmLiteDialectProvider. Specifically, I would override the GetAutoIdDefaultValue method to return "SYS_GUID()" if the field type is a GUID. Sample code below...
public OracleNewGuidOrmLiteDialectProvider : OracleOrmLiteDialectProvider
{
public static OracleNewGuidOrmLiteDialectProvider Instance = new OracleNewGuidOrmLiteDialectProvider();
public string AutoIdGuidFunction { get; set; } = "SYS_GUID()";
public override string GetAutoIdDefaultValue(FieldDefinition fieldDef)
{
return fieldDef.FieldType == typeof(Guid)
? AutoIdGuidFunction
: null;
}
}
To match the rest of the provider implementations, I would recommend creating a OracleNewGuidDialect class, like below...
public static class OracleNewGuidDialect
{
public static IOrmLiteDialectProvider Provider => OracleNewGuidOrmLiteDialectProvider.Instance;
}
Then you would set the provider when you instantiate your OrmLiteConnectionFactory to OracleNewGuidOrmLiteDialectProvider.Instance, similar to below...
var dbFactory = new OrmLiteConnectionFactory(oracleConnectionString, OracleNewGuidDialect.Provider);
This isn't the best solution, but the pluggable nature of ServiceStack ORMLite allows you to control everything to the extent that you need. Hope this helps. Also, quick caveat--I didn't fully bake this solution, so you may need to tweak it, but based on the other implementations of the providers, it seems straightforward.
Code:
public interface IServices
{
[OperationContract]
[XmlSerializerFormat]
GetProductsResponse Getproducts(GetProductsRequest productsrequest);
[OperationContract]
SaveProductsResponse SaveProducts1(SaveProductsRequest1 productsrequest);
}
[DataContract]
public class SaveProductsRequest1
{
[DataMember]
public List<Person> Persons;
}
[DataContract]
public class Person
{
[DataMember]
public int Id;
}
Client :
ServicesClient client = new ServicesClient();
SaveProductsRequest1 req = new SaveProductsRequest1();
req.Persons = new List<Person> { new Person { Id = 10 } }.ToArray();
client.SaveProducts1(req);
I am invoking the SaveProducts1 call from client side and not able to get the value '10' in my service side(seems deserialization issue). But when I remove [XmlSerializerFormat] attribute from Getproducts call, it just works fine and I am able to see the value 10.
Why is it happening(Why SaveProducts1 depends on Getproducts OperationContract)? What workaround I should provide, when I want to use both xml and datacontract serialization? Any help appreciated.
Note: I have very updated proxy. I am not seeing any issue in proxy. Even I tried with one sample and getting the same issue
Did you refresh your client service reference after adding the XmlSerializerFormat attribute? It could be that the contracts don't match any longer.
I have several variables that I need to send from page to page...
What is the best way to do this?
Just send them one by one:
string var1 = Session["var1"] == null ? "" : Session["var1"].ToString();
int var2 = Session["var2"] == null ? 0 : int.Parse(Session["var2"].ToString());
and so on...
Or put them all in some kind of container-object?
struct SessionData
{
public int Var1 { get; set; }
public string Var2 { get; set; }
public int Var3 { get; set; }
}
--
SessionData data = Session["data"] as SessionData;
What is the best solution? What do you use?
A hybrid of the two is the most maintainable approach. The Session offers a low-impedance, flexible key-value pair store so it would be wasteful not to take advantage of that. However, for complex pieces of data that are always related to each other - for example, a UserProfile - it makes sense to have a deeply nested object.
If all the data that you're storing in the Session is related, then I would suggest consolodating it into a single object like your second example:
public class UserData
{
public string UserName { get; set; }
public string LastPageViewed { get; set; }
public int ParentGroupId { get; set; }
}
And then load everything once and store it for the Session.
However, I would not suggest bundling unrelated Session data into a single object. I would break each seperate group of related items into their own. The result would be something of a middleground between the two hardline approaches you provided.
I use a SessionHandler, which is a custom rolled class that looks like this
public static class SessionHandler
{
public static string UserId
{
get
{
return Session["UserId"];
}
set
{
Session["UserId"] = value;
}
}
}
And then in code I do
var user = myDataContext.Users.Where(u => u.UserId = SessionHandler.UserId).FirstOrDefault();
I don't think I've every created an object just to bundle other objects for storage in a session, so I'd probably go with the first option. That said, if you have such a large number of objects that you need to bundle them up to make it easier to work with, you might want to re-examine your architecture.
I've used both. In general, many session variable names leads to a possibility of collisions, which makes collections a litte more reliable. Make sure the collection content relates to a single responsibility, just as you would for any object. (In fact, business objects make excellent candidates for session objects.)
Two tips:
Define all session names as public static readonly variables, and make it a coding standard to use only these static variables when naming session data.
Second, make sure that every object is marked with the [Serializable] attribute. If you ever need to save session state out-of-process, this is essential.
The big plus of an object: properties are strongly-typed.
Suppose I use the [RemoteClass] tag to endow a custom Flex class with serialization intelligence.
What happens when I need to change my object (add a new field, remove a field, rename a field, etc)?
Is there a design pattern for handling this in an elegant way?
Your best bet is to do code generation against your backend classes to generation ActionScript counterparts for them. If you generate a base class with all of your object properties and then create a subclass for it which is never modified, you can still add custom code while regenerating only the parts of your class that change. Example:
java:
public class User {
public Long id;
public String firstName;
public String lastName;
}
as3:
public class UserBase {
public var id : Number;
public var firstName : String;
public var lastName : String;
}
[Bindable] [RemoteClass(...)]
public class User extends UserBase {
public function getFullName() : String {
return firstName + " " + lastName;
}
}
Check out the Granite Data Services project for Java -> AS3 code generation.
http://www.graniteds.org
Adding or removing generally works.
You'll get runtime warnings in your trace about properties either being missing or not found, but any data that is transferred and has a place to go will still get there. You need to keep this in mind while developing as not all your fields might have valid data.
Changing types, doesn't work so well and will often result in run time exceptions.
I like to use explicit data transfer objects and not to persist my actual data model that's used throughout the app. Then your translation from DTO->Model can take version differences into account.