SQLite.net使用外键进行插入

时间:2016-04-12 14:31:40

标签: sqlite insert foreign-keys mvvmcross

正确保存数据库的最佳解决方案是什么: 我想在我的sqlite数据库中保存这些数据并将其导出为CSV,我做了一个小方法,但是通过这个过程,我无法在我的EmailEntity中获得PhotoEnt。

PhotoEntity:

 public class PhotoEntity : EntityBase
{
    [PrimaryKey, AutoIncrement]
    public override int Id { get; set; }

    public string IdGuid { get; set; }

    public string PhotoDate { get; set; }

    public string Image { get; set; }

    [OneToMany]
    public List<EmailEntity> Emails { get; set; }
}

EmailEntity:

public class EmailEntity : EntityBase
{
    [PrimaryKey, AutoIncrement]
    public override int Id { get; set; }

    [ForeignKey(typeof (PhotoEntity))]
    public string IdGuid { get; set; }

    public string Email { get; set; }

    [ManyToOne]
    public PhotoEntity PhotoEnt { get; set; }
}

而且,当我保存时,我会这样做:

private void DoInsertBddCommand()
    {
        var guidForId = Guid.NewGuid().ToString();
        var dateTime = DateTime.Now.ToString();

        var photoEntity = new PhotoEntity
        {
            IdGuid = guidForId,
            Image = _imageName,
            PhotoDate = dateTime
        };
        new PhotoBusiness().Save(photoEntity);

        foreach (var item in Emails)
        {
            var emailEntity = new EmailEntity
            {
                IdGuid = guidForId,
                Email = item,
                PhotoEnt = photoEntity
            };

            new EmailBusiness().Save(emailEntity);
        }
    }

这是我第一次使用SQLite.net,有什么建议吗?

谢谢

1 个答案:

答案 0 :(得分:1)

好的,这就是我如何设置你的模型:

 public class PhotoEntity : EntityBase
{
    [PrimaryKey, AutoIncrement]
    public override int Id { get; set; }

    public string PhotoDate { get; set; }

    public string Image { get; set; }

    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<EmailEntity> Emails { get; set; }
}

public class EmailEntity : EntityBase
{
    [PrimaryKey, AutoIncrement]
    public override int Id { get; set; }

    [ForeignKey(typeof (PhotoEntity))]
    public int PhotoEntityId { get; set; }

    public string Email { get; set; }

    [ManyToOne(CascadeOperations = CascadeOperation.All)]
    public PhotoEntity PhotoEnt { get; set; }
}

请注意,我在关系属性中定义了级联操作。这直接来自SQLite-Extensions文档:https://bitbucket.org/twincoders/sqlite-net-extensions#markdown-header-cascade-operations

现在,当您保存/检索对象时,需要使用递归方法:

GetWithChildren
InsertWithChildren

https://bitbucket.org/twincoders/sqlite-net-extensions#markdown-header-cascade-read