c# - 通过 DataAnnotation 强制外键列名称不起作用

标签 c# ef-code-first data-annotations entity-framework-5

好的,我有两个类:“计划”和“ Material ”。一个计划有 0..1 个 Material ,一个 Material 可以包含在多个计划中。创建数据库时,自动生成的列名为 Material_MaterialId,我希望将其命名为 MaterialId

我的“计划”类(class):

[Column("MaterialId")]
public virtual Material Material { get; set; }

我的“ Material ”类(class):

public int MaterialId { get; set; }

但它似乎没有做任何事情。

最佳答案

你应该使用这个:

计划类

public virtual Material Material { get; set; }

public int? MaterialId { get; set; } /* it prompt clr create foreign key MatherialId which referenced to MatherialId class of Matherial */

Material 类

public int MaterialId { get; set; }

已更新

完整解决方案

实体:

namespace MvcApplicationTest.Models
{
    public class Material
    {
        public int MaterialId { get; set; }
        public int Name { get; set; }
    }

    public class Plan
    {
        public int PlanId { get; set; }
        public int Name { get; set; }

        //full navigation property
        public virtual Material Material { get; set; }
        public int? MaterialId { get; set; } 
        //

    }

    public class TestContext : DbContext
    {
        public DbSet<Material> Materials { get; set; }
        public DbSet<Plan> Plans { get; set; }
    }
}

global.asax 中的一些初始化:

var context = new TestContext();
context.Database.CreateIfNotExists();

结果应该是这样的:

enter image description here

你的名字:

 [ForeignKey("MaterialFK")]
 public virtual Material MyMaterial { get; set; } //your name
 public int? MaterialFK { get; set; } //your name

关于c# - 通过 DataAnnotation 强制外键列名称不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12834293/

相关文章:

c# - .NET MVC 自定义日期验证器

c# - C/C#-编码(marshal).PtrToStringAnsi

c# - DirectX - 顶点缓冲区中的一半而不是 float

asp.net-mvc - Entity Framework Code First 数据库文件未在 APP_DATA 中创建,但查询有效

.net - Entity Framework : Can't use "Contains" with property on another object

entity-framework - Entity Framework Code First - 单类多对多

c# - 拆分实体数据模型属性的数据注释 [必需] 属性

c# - 将文件上传到 Google Team Drive

c# - WPF Ribbon AuxiliaryPaneContent 隐藏或折叠

asp.net 4.5 webforms模型绑定(bind): client side validation supported?