简体   繁体   中英

ManyToMany Relation → Add a value to the junction table

I have two entities: Component and Attribute. Components can have multiple Attributes and Attributes can also have multiple Components. The value of the attribute will be stored in the junction table "ComponentAttribute". I don't know whats the best way to add the value.

public class Component
{
    [PrimaryKey, AutoIncrement]
    public int id { get; set; }

    [ManyToMany(typeof(ComponentAttribute))]
    public List<Attribute> attributes { get; set; }
}
public class Attribute
{
    [PrimaryKey, AutoIncrement]
    public int id { get; set; }
    public string name { get; set; }

    [ManyToMany(typeof(ComponentAttribute))]
    public List<Component> components { get; set; }
}
public class ComponentAttribute
{
    [PrimaryKey, AutoIncrement]
    public int id { get; set; }

    public string value { get; set; }

    [ForeignKey(typeof(Component))]
    public int componentId { get; set; }

    [ForeignKey(typeof(Attribute))]
    public int attributeId { get; set; }
}
Attribute attribute = new Attribute();
Attribute attribute2 = new Attribute();
Component component = new Component();

component.attributes.Add(attribute);
component.attributes.Add(attribute2);

this.dbConnection.Insert(attribute);
this.dbConnection.Insert(attribute2);
this.dbConnection.Insert(component);
this.dbConnection.UpdateWithChildren(component);

// After this I have to load the new ComponentAttributes and add the value manual

So it would be nice, if someone could give me a hint how to access the value

Unfortunately, you cannot do this.

SQLite-Net-Extensions uses InsertAll method inside Many-To-Many relationships handler and inserting only that properties which marked as ForeignKey into database table.

Best workaround is that you using in question.
Load ComponentAttributes entity from database by known data ( Attribute.id and Component.id ) and then update value of recieved ComponentAttribute object by primary key ( ComponentAttribute.id ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM