2
votes

I am using ORMLite as my ORM and I am using it with following structure which contains the foreign key relation ship:

 public class Order
    {
        [AutoIncrement]
        public int Id { get; set; }

        [Reference]
        public Item Item { get; set; }

        public string ProUserId { get; set; }

        public string Details { get; set; }
    }

    public class Item
    {
        [AutoIncrement]
        public int Id { get; set; }
        public string Description { get; set; }
    }

As we can see that Order contains the reference to the Item. In DB Order table has a foreign key called ItemId in the table and I have annotated that key in the design view with [Reference] attribute.

I am trying to save the Order with following code:

var order = new Order
                {
                    Item = new Item
                    {
                        Id  = 3,
                        Description = "Something"
                    },

                    ProUserId = "[email protected]",
                    Details = "fdfsdfsd"

                };

                Db.Save(order,references:true);

I was hoping that ORMLite would pick up the relationship and with ItemID in the Order table but it did not and it did throw following error instead:

Cannot insert the value NULL into column 'ItemId', table 'WebApp.dbo.Order'; column does not allow nulls. INSERT fails.

I tried changing my schema and addred OrderId column in my Item table with reference there and that works fine. But that is not the correct design. Should I make any changes in my code/schema to support this feature?

1

1 Answers

2
votes

You still need to provide the foreign key that OrmLite can use to store the relationship, e.g. either on the Child/ForeignKey table:

public class Order
{
    [AutoIncrement]
    public int Id { get; set; }

    [Reference]
    public Item Item { get; set; }

    public string ProUserId { get; set; }

    public string Details { get; set; }
}

public class Item
{
    [AutoIncrement]
    public int Id { get; set; }
    public int OrderId { get; set; }  //Parent Table PK
    public string Description { get; set; }
}

Or for 1:1 relationships, can be on the Parent table, e.g:

public class Order
{
    [AutoIncrement]
    public int Id { get; set; }

    [Reference]
    public Item Item { get; set; }

    public int ItemId { get; set; }  //Child Table PK

    public string ProUserId { get; set; }

    public string Details { get; set; }
}

public class Item
{
    [AutoIncrement]
    public int Id { get; set; }
    public string Description { get; set; }
}