c#实体框架外键

时间:2017-01-05 10:38:35

标签: entity-framework foreign-keys

我是新来的,希望我能得到一个答案 - 我两天都在网上搜索......

这是我第一次在Windows 10 UWP中使用实体framewort。我必须使用作为数据库对象的类。在一个对象中,我使用另一个类型的属性。 如果我尝试添加记录,我会收到错误。

public class budgetcontext : DbContext
{
    private string myDB = "Filename=budget_4.db";

    public DbSet<category> Categories { get; set; }
    public DbSet<transaction> Transactions { get; set; }

    public budgetcontext()
    {
        this.Database.Migrate();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite(myDB);
    }
}

public class category
{
    private string myGuid = Guid.NewGuid().ToString();

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public double BudgetDaily { get; set; }
    public double BudgetWeekly { get; set; }
    public double BudgetMonthly { get; set; }
    public double BudgetYearly { get; set; }

    public string CategoryGuid
    {
        get
        {
            return myGuid;
        }
    }

}

public class transaction
{
    private string myGuid = Guid.NewGuid().ToString();

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Int64 TransactionId { get; set; }
    public string Text { get; set; }
    public category Category { get; set; }
    public DateTime TransDateTime { get; set; }
    public double Amount { get; set; }
}

如果我尝试将类型事务的记录插入数据库,我将收到错误:

{“SQLite错误19:'UNIQUE约束失败:Categories.CategoryId'。”}

插入对象的代码是:

budget_sqlite.category c = cbCategory.SelectedItem as budget_sqlite.category; //Object is selected in a Combo

using (var db = new budget_sqlite.budgetcontext())
        {
            t.Text = this.txtText.Text;
            t.Category = c;
            t.TransDateTime = new DateTime(dpDate.Date.Year, dpDate.Date.Month, dpDate.Date.Day, tpTime.Time.Hours, tpTime.Time.Minutes, tpTime.Time.Seconds);

            double.TryParse(txtAmount.Text, out value);

            if (RBOut.IsChecked == true)
            {
                value = value * -1;
            }

            t.Amount = value;

            if (t.TransactionId == 0)
            {
                db.Transactions.Add(t);
            }

            db.SaveChanges();
        }

以下是迁移:

[DbContext(typeof(budgetcontext))]
partial class budgetcontextModelSnapshot : ModelSnapshot
{
    protected override void BuildModel(ModelBuilder modelBuilder)
    {
        modelBuilder
            .HasAnnotation("ProductVersion", "1.1.0-rtm-22752");

        modelBuilder.Entity("budget_sqlite.category", b =>
            {
                b.Property<int>("CategoryId")
                    .ValueGeneratedOnAdd();

                b.Property<double>("BudgetDaily");

                b.Property<double>("BudgetMonthly");

                b.Property<double>("BudgetWeekly");

                b.Property<double>("BudgetYearly");

                b.Property<string>("Name");

                b.HasKey("CategoryId");

                b.ToTable("Categories");
            });

        modelBuilder.Entity("budget_sqlite.transaction", b =>
            {
                b.Property<long>("TransactionId")
                    .ValueGeneratedOnAdd();

                b.Property<double>("Amount");

                b.Property<int?>("CategoryId");

                b.Property<string>("Text");

                b.Property<DateTime>("TransDateTime");

                b.HasKey("TransactionId");

                b.HasIndex("CategoryId");

                b.ToTable("Transactions");
            });

        modelBuilder.Entity("budget_sqlite.transaction", b =>
            {
                b.HasOne("budget_sqlite.category", "Category")
                    .WithMany()
                    .HasForeignKey("CategoryId");
            });
    }
}

public partial class V0001 : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Categories",
            columns: table => new
            {
                CategoryId = table.Column<int>(nullable: false)
                    .Annotation("Sqlite:Autoincrement", true),
                BudgetDaily = table.Column<double>(nullable: false),
                BudgetMonthly = table.Column<double>(nullable: false),
                BudgetWeekly = table.Column<double>(nullable: false),
                BudgetYearly = table.Column<double>(nullable: false),
                Name = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Categories", x => x.CategoryId);
            });

        migrationBuilder.CreateTable(
            name: "Transactions",
            columns: table => new
            {
                TransactionId = table.Column<long>(nullable: false)
                    .Annotation("Sqlite:Autoincrement", true),
                Amount = table.Column<double>(nullable: false),
                CategoryId = table.Column<int>(nullable: true),
                Text = table.Column<string>(nullable: true),
                TransDateTime = table.Column<DateTime>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Transactions", x => x.TransactionId);
                table.ForeignKey(
                    name: "FK_Transactions_Categories_CategoryId",
                    column: x => x.CategoryId,
                    principalTable: "Categories",
                    principalColumn: "CategoryId",
                    onDelete: ReferentialAction.Restrict);
            });

        migrationBuilder.CreateIndex(
            name: "IX_Transactions_CategoryId",
            table: "Transactions",
            column: "CategoryId");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "Transactions");

        migrationBuilder.DropTable(
            name: "Categories");
    }
}

非常感谢你的帮助。

0 个答案:

没有答案