Map to custom column names with ServiceStack OrmLite (Without Attributes) - servicestack

Per title - Is it possible to map
class Test {
String SomeName {get; set;}
}
to SQL Table
tbl_test (name)
I am not interested to use attributes as I don't want to fill my POCOs with garbage.
Thanks.

Since all ServiceStack libraries use the metadata API's in ServiceStack.Text, all attributes can also be added decoupled from the model itself using the fluent API below:
typeof(Test)
.AddAttributes(new AliasAttribute("tbl_test"));
To add attributes on a property you can use the GetProperty() extension method, e.g:
typeof(Test)
.GetProperty("SomeName")
.AddAttributes(new AliasAttribute("p_some_name"));
These attributes need to be run once on Startup before they're accessed by any ServiceStack library.

Related

How to manage separation of concerns when using ServiceStack AutoQuery

I am having some issues with how to organise my AutoQuery code. My project structure currently looks like:
/Project
/Project.ServiceInterface
Service.cs
/Project.Logic
Manager.cs
/Types
DbModel.cs
/Project.ServiceModel
Request.cs
/Types
DtoModel.cs
With this setup, the ServiceModel has no knowledge of the Logic models. Because of this, I can't make a request query like QueryDb<DbModel, DtoModel> without essentially duplicating all my DbModel objects in my ServiceModel or adding a dependency to Logic in ServiceModel. I also have custom AutoQuery service implementations and inside those I want to be able to leverage code that has been written using my DbModels elsewhere.
Does anyone have any recommendations or relevant examples? I feel like I'm approaching this problem incorrectly and making it more complex than need be. Thanks.
Auto Query lets you create Services by defining a Request DTO as such all Types it references must also be the ServiceModel Assembly, so you'd either need to move the Data Models your AutoQuery Services references to your ServiceModel project or annotate your DTO so that it can be used by OrmLite to query your RDBMS Table where it can use the [Alias] attribute where names differ and the [Ignore*] attributes depending on whether the property should exist in OrmLite or Serialization, e.g:
[Alias("MyTable")]
public class MyDto
{
[Alias("DbName")]
public string DtoName { get; set; }
[Ignore]
public string IgnoredInOrmLite { get; set; }
[IgnoreDataMember]
public string IgnoredInSerialization { get; set; }
}
Otherwise you're not going to be able to use Auto Query and would need to create Custom Services whose internal implementation makes use of your Data Models where they're hidden from your public Services Contract.
Personally I'd recommend moving the Data Models you need to your ServiceModel Assembly (that continues to use the same Namespace as your other DataModels) as OrmLite DataModels are POCOs that like DTOs typically don't need any additional references other than the impl-free ServiceStack.Interfaces.

When to use DTO's and Models for ServiceStack?

I've seen quite some examples of ServiceStack services and I don't seem to understand when to use a DTO and when to use a Model. As I understand it the DTO is to keep everything as seperate as possible as it's the contract of your service. That would allow you to change a lot in your code but keep the DTO's unchanged. But if you have a Model as one of the properties or it's return value (in a lot of examples that's what I see), the dependency on the model is there any way, so why not simply wrap the Model in the DTO for the request as well?
[Route("/events", "POST")]
public class CreateEvent : IReturn<Event>
{
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
From: Recommended ServiceStack API Structure
/// <summary>
/// Define your ServiceStack web service response (i.e. Response DTO).
/// </summary>
public class MovieResponse
{
/// <summary>
/// Gets or sets the movie.
/// </summary>
public Movie Movie { get; set; }
}
From: https://github.com/ServiceStack/ServiceStack.Examples/blob/master/src/ServiceStack.MovieRest/Web/MovieService.cs
You would use distinct DTO's for Data Models that make poor substitutes for serializable DTO's, e.g:
Have cyclical dependencies or overuse of Inheritance and interfaces
This is less of an issue when using code-first ORM's like OrmLite which as they encourage use of clean POCO's already make good candidates to be re-used as DTO's.
Ideally DTO's should be self-describing and non-hierarchical (i.e. flat) and not rely on serializer-specific features, inhibiting re-usability and reducing interoperability with different formats and serializers.
Doesn't match the shape of the Contract that you want to expose
Your data models might make use of internal codes (e.g. int values) which doesn't make sense to external users outside your database, in which case you may want to project them into self-describing DTO's which exposes more user-friendly labels.
You can use Auto Mapping to reduce the effort whenever you need to re-project between models.

How can i write attributes in model while using entity frame work Database first approch

I'm developing an application using asp.net mvc 5 and entity framework 6. I have generated model classes from database and set some attributes to entities in model class. But these attributes are gets cleared each time I refresh the entity model. I know this is because the model classes are generated from database. Then how can I specify additional attributes in entity frame work db first approach?
You need to specify a metadata class. Say your model class is Employee. You would create a separate partial class file for Employee and define the metadata type.
[MetadataType(typeof(EmployeeMetadata))]
public partial class Employee
{
}
DO NOT add the above attribute to your generated Employee.cs. Create a separate file (e.g. EmployeePartial.cs).
Then you would create EmployeeMetadata class and define the attributes you want.
public class EmployeeMetadata
{
[StringLength(100)]
public string LastName { get; set; }
}

Designing DTO's and DO service layer

I'm designing a new large scale application which needs to be as flexible as possible.
I chose designing mainly with DDD..
My question is about transferring DTO object's back to DO objects in my service layer.
i.e:
This is my domain object mapped to the DB (using ORM)
public class Cat
{
int ID {get; set;}
string Name {get; set;}
string BloodType {get; set;}
string Color {get; set;}
void Run(){...}
void Purr() {...}
}
Methods and some properties are only needed for server actions.
That's why I designed another, data transfer object for this cat type:
public class CatDTO
{
int ID {get; set;}
string Name {get; set;}
}
In the middle, I'll set up an object mapper to translate my DO's to DTO's (and vice versa).
When a client would like to update a cat's name he will call a service like this
public void UpdateCat(CatDTO cat)
{
// What will happen here?
Cat serverCat = Mapper.GetCat(CatDTO);
CatDao.SaveOrUpdate(serverCat);
}
When the mapper is translating the DTO object back to DO it will have to hit the DB in order to fill the missing properties of the Cat object (blood type, etc')
Needles to say this action is absurd but without filling the empty properties the rest of the server side cannot work with the Cat object because it relies on those missing properties (even if i just try to update the data in the DB, My ORM will update the bloodtype field as an empty string!)
I searched for this problem and couldn't find any explenation on the web (or at least someone who is bothered with the issue as I do)
Am I designing it the wrong way? Maybe I missed something in my DDD?
Thanks, Pavel.
The usual workflow for this use case is: retrieve mapped domain object by ID, apply updates specified by the DTO, commit unit of work. What you refer to as the DAO is normally called a repository in DDD. The code should look more like:
public void UpdateCat(CatDTO catDto)
{
Cat cat = this.catRepository.Get(cat.ID);
cat.Name = catDto.Name;
this.catRepository.Commit();
}
The Commit step can come in a variety of ways. It can either be an explicit save, or the unit of work can be committed outside of the UpdateCat method. This workflow applies to all related scenarios as well. Generally, domain behavior involves retrieving the appropriate entity, invoking some behavior on that entity and then committing the resulting changes to the database.
Also, DTOs shouldn't directly map back into existing entities. Instead, it is better to think of them as representing changes to be applied to existing entities and the code should reflect this. This is in part because an existing entity is "owned" by the repository and the repository is responsible for reconstitution, not a DTO mapper.

Azure TableStorage HowTo?

I want to store Contacts on to Azure table(name and gender as a property). so I basically two classes . the one which derives from the TableSerivceContext and the other from TableServiceEntity. now I cant connect the pieces. What I will really do at the cotroller(I use MVC3)
tnx for any hint?
im assuming that you are receiving the properties (name and gender) via post from a view.
so your controller might be like this
public ActionResult DoSomething(User model)
{
}
so what you need to do is.. that. make a new ofject of the class thats derived from the TableServiceEntity. and assign the Properties.
like this
var tableUser = new TableUser(){Name = model.Name, Gender=model.Gender}
then from the class derived from TableServiceContext make an object. and use AddObject() method to add the user to the table
http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.addobject.aspx
This is what I have done recently to create a very simple MVC3 + Windows Azure Table sample application:
Created a Model Class DataEntity inherit from TableServiceEntity which include all the table properties needed to store along with PartitionKey and RowKey
Created another Model class DataContext inherit from TableServiceConext which includes IQueryable sets up the Table
Created a Controller class which creates HTTPGet and HTTPPost method type ViewResult returning View. The controller also have code to create the Table first using Model DataContext type and then added code to call AddObject as DataEntity type as below:
DataContext context = new DataContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
context.AddObject("DataEntryTable", dataEntity);
context.SaveChanges();
Finally you can create views from the controllers.
You would need to inherit ‘Contact’ from TableServiceEntity and a context class from TableServiceContext to provide all the methods to manage your ‘Contact’ entities. You can then invoke methods on the ‘Context’ class from anywhere (including the controller).
I have written an alternate Azure table storage client, Lucifure Stash, which does away with having to inherit from any base calls and supports additional abstractions over azure table storage. Lucifure Stash supports large data columns > 64K, arrays & lists, enumerations, composite keys, out of the box serialization, user defined morphing, public and private properties and fields and more.
It is available free for personal use at http://www.lucifure.com or via NuGet.com.
Download the Windows Azure Platform Training Kit and do the lab on Windows Azure Storage. In 15 minutes you will have a working prototype.

Resources