CoolStorage can't set One-To-One relationship

85 views Asked by At

The issue is that I can't understand how to make a OneToOne relation between two objects the way for the first object to have a link to the second and for the second to have a link to the first. Here's the code:

[MapTo("Model")]
public class Model : CSObject<Model, int>
{
    [OneToOne(LocalKey = "ModelID", ForeignKey = "ModelID")]
    public Product Product { get { return (Product)GetField ("Product"); } set { SetField ("Product", value); } } 
}

[MapTo("Product")]
public class Product : CSObject<Product, int>
{
    [OneToOne(LocalKey = "ProductID", ForeignKey = "ProductID")]
    public Model Model { get { return (Model)GetField ("Model"); } set { SetField ("Model", value); } }
}

The thing is that when I create a product and a model and set the model's property "Product" to the created one and save it, the product's "Model" property doesn't get set and remains NULL. I've already tried making all the local and foreign keys for both Product's and Model's properties the same (e.g. "ModelID") but it didn't solve the problem. What is the right way of doing this?

I guess making one of them [OneToMany] will do the trick but will return a collection while I need a single object to be returned by a property.

Update

Here comes a simple solution one would call a crutch:

[OneToMany]
public CSList<Product> _ProductList { get { return (CSList<Product>)GetField ("_ProductList"); } set { SetField ("_ProductList", value); } }

[NotMapped]
public Product Product {
    get {
        CSList<Product> list = this._ProductList;
        if (list.Count > 0)
            return list [0];
        return null;
    }
    set {
        if (value != null) {
            CSList<Product> list = this._ProductList;
            list.RemoveAll ();
            list.Add (value);
        }
    }
}
1

There are 1 answers

1
Philippe Leybaert On

You can make both relations [ManyToOne]. That will work in your scenario.