Archana
Archana

Reputation: 105

Composite key in Entity Framework using sqlite in uwp

I am developing an uwp app. I am using entity models to create tables in sqlite database. I have a situation with a table where 2 columns make up the primary key. But I am not able to create a table with composite key.

The code I have used for table creation is:

public class Denomination_Master
{
        [MaxLength(50), NotNull]
        public string den_name { get; set; }
        [NotNull,PrimaryKey]
        public float den_value { get; set; }
        [MaxLength(50), Indexed]
        public string den_type { get; set; }
        [MaxLength(250), Default(value: null)]
        public string den_image { get; set; }
        [MaxLength(250), Default(value: null)]
        public string description { get; set; }
        [Default(value: null)]
        public string created_date { get; set; }
        [Default(value: null)]
        public string updated_date { get; set; }
        [MaxLength(80), Default(value: null)]
        public string role_name { get; set; }
        [MaxLength(80), Default(value: null)]
        public string user_name { get; set; }
        [MaxLength(4), Default(value: null)]
        public bool? status { get; set; }
}

using (SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), sqlpath))
{
    conn.CreateTable<Denomination_Master>();
}

https://github.com/oysteinkrog/SQLite.Net-PCL here I found something like this:

    public class Stock
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [MaxLength(8)]
    public string Symbol { get; set; }
}

public class Valuation
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [Indexed]
    public int StockId { get; set; }
    public DateTime Time { get; set; }
    public decimal Price { get; set; }
}

But my column datatype is not int how can apply this.?

Upvotes: 1

Views: 1377

Answers (1)

ErikEJ
ErikEJ

Reputation: 41799

You need to define your composite key using the fluent API, you cannot use attributes for composite primary keys.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Denomination_Master>()
        .HasKey(c => new { c.den_value, c.den_type });
}

https://learn.microsoft.com/en-us/ef/core/modeling/keys

Upvotes: 2

Related Questions