public class User {
public string Id { get; set; }
public string Name { get; set; }
public EntityRef<Company> Company { get; set; }
}
public class Company {
public string Id { get; set; }
public string Name { get; set; }
}
public class EntityRef {
private dynamic entity;
public EntityRef(string entityId) {
this.Id = entityId;
}
public EntityRef(dynamic entity) {
this.Entity = entity;
}
[JsonIgnore]
public dynamic Entity {
get { return this.entity; }
set {
this.entity = value;
this.Id =
this.entity.Id;
this.HasEntity = true;
}
}
[JsonIgnore]
public bool HasEntity { get; private set; }
public string Id { get; set; }
public static implicit operator EntityRef(string entityId) {
return new EntityRef(entityId);
}
}
public class EntityRef<T> : EntityRef {
public EntityRef(T entity) : base(entity) {}
public EntityRef(string entityId) : base(entityId) {}
[JsonIgnore]
public new T Entity {
get { return base.Entity; }
set { base.Entity = value; }
}
public static implicit operator EntityRef<T>(T entity) {
return new EntityRef<T>(entity);
}
public static implicit operator EntityRef<T>(string entityId) {
return new EntityRef<T>(entityId);
}
public static implicit operator T(EntityRef<T> entityRef) {
return entityRef.Entity;
}
}
internal class Program {
private static void Main(string[] args) {
var user = new User {
Id = "users/oren",
Name = "Oren",
Company = "companies/hibernating-rhinos"
};
var company = new Company {
Id = "companies/hibernating-rhinos",
Name = "Hibernating Rhinos"
};
user.Company = company;
var session = new Program();
session.Store(user);
session.Delete(user);
Console.WriteLine(
user.Company.Entity.Name);
Console.WriteLine(JObject.FromObject(user));
Console.ReadLine();
}
public void Store(object entity) {
// If entity is already stored in current session then return
// Store entity
Console.WriteLine("Stored " + entity);
foreach (var referencedEntity in
GetReferencedEntities(entity))
this.Store(referencedEntity);
}
public void Delete(object entity) {
// If entity is already deleted in current session then return
// Delete entity
Console.WriteLine("Delete " + entity);
foreach (var referencedEntity in
GetReferencedEntities(entity))
this.Delete(referencedEntity);
}
private static IEnumerable<dynamic> GetReferencedEntities(object
entity) {
return from property in entity.GetType().GetProperties()
where property.PropertyType.IsSubclassOf(typeof
(EntityRef))
let reference = (EntityRef) property.GetValue(entity,
null)
where reference.HasEntity
select reference.Entity;
}
}
On Aug 9, 4:19 pm, Ayende Rahien <
aye...@ayende.com> wrote:
> Can you suggest an API for this?
>
>
>
> On Mon, Aug 9, 2010 at 2:14 PM, Ernst Naezer <
ernstnae...@gmail.com> wrote:
> > of maybe this is something that can be fixed using dynamics? It's afterall
> > a dynamic object you're constructing
>