简体   繁体   中英

How to create two foreign keys to the same table with SQLite in Xamari Form

I working in a project with Xamarin Form using C#. I'm trying to create two foreign keys to the same table, using this code:

[Table("Posts")]
public class Post
{
    [PrimaryKey]
    public long PostID { get; set; }
    public string Name { get; set; }

    public TypeEntity mode = null;
    [ManyToOne(CascadeOperations = CascadeOperation.CascadeInsert)]
    public TypeEntity Mode
    {
        get
        {
            return mode;
        }
        set
        {
            mode = value;
        }
    }
    [ForeignKey(typeof(TypeEntity))]
    public long ModeID { get; set; }

    public TypeEntity level = null;
    [ManyToOne(CascadeOperations = CascadeOperation.CascadeInsert)]
    public TypeEntity Level
    {
        get
        {
            return level;
        }
        set
        {
            level = value;
        }
    }
    [ForeignKey(typeof(TypeEntity))]
    public long LevelID { get; set; }
}

[Table("Types")]
public class TypeEntity
{
    [PrimaryKey]
    public long TypeID { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

As you can see, the properties Mode and Level are type "TypeEntty", so I need to create the relations. When I try to insert data, only "Mode" property is inserted ok, "Level" property stay null.

public abstract class BaseStore<T> where T : new()
{
    public static SQLiteConnection sql;

    public BaseStore()
    {
        sql = DependencyService.Get<ISQLite>().GetConnection();
        Init();
    }
    public void Init()
    {
        sql.CreateTable<T>();
    }

    public void Insert(T entity)
    {
        sql.InsertWithChildren(entity);
    }
}

I switched properties order, I added Level first than Mode, and Level got the value. It means, that SQLIte take only the first property to create the relation.

Does anyone know why this isn't working?

I'm working with SQLite.Net.Core-PCL 3.1.1 and SQLiteNetExtensions 2.1.0.

You have to manually specify which foreign key corresponds to each relation. To do so, pass the ForeignKey parameter in each ManyToOne attribute.

Can't test it right now, but it would probably look something like this:

[ManyToOne(ForeignKey = "ModeID", CascadeOperations = CascadeOperation.CascadeInsert)]
public TypeEntity Mode

(...)

[ManyToOne(ForeignKey = "LevelID", CascadeOperations = CascadeOperation.CascadeInsert)]
public TypeEntity Level

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