Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 有主键和辅键这样的东西吗?_C#_Sql Server_Entity Framework_Ef Code First_Primary Key - Fatal编程技术网

C# 有主键和辅键这样的东西吗?

C# 有主键和辅键这样的东西吗?,c#,sql-server,entity-framework,ef-code-first,primary-key,C#,Sql Server,Entity Framework,Ef Code First,Primary Key,我有这样的想法: public class something { [Key] public int Id {get;set;} public string Name {get;set;} } public class secondsomething { [Key] public int Id {get;set;} [ForeignKey("Sth") {get;set;} public int sthId{get;set;} public so

我有这样的想法:

public class something {
   [Key]
   public int Id {get;set;}
   public string Name {get;set;}
}

public class secondsomething {
   [Key]
   public int Id {get;set;}
   [ForeignKey("Sth") {get;set;}
   public int sthId{get;set;}
   public something Sth{get;set;}
}
我想要这个:

public class something {
   [Key]
   public int Id {get;set;} //keep this as primary key
   public string Name {get;set;} //maybe somehow mark this as a secondary key
}

public class secondsomething {
   [Key]
   public int Id {get;set;}
   [ForeignKey("Sth") {get;set;}
   public string sthName{get;set;} //don't want the id here, but it's name
   public something Sth{get;set;}
}

有没有办法做到这一点?

您可能会发现代码优先迁移工具在满足索引要求方面很有用。
参见

正如Gert Arnold所说,没有直接支持首先在代码上定义索引,但是如果使用迁移,可以直接调用Sql()方法并在那里定义它。下面是一个例子:

public partial class AddingUsernameIndexes : DbMigration
{
    public override void Up()
    {
        Sql("CREATE NONCLUSTERED INDEX IX_Applications_Username ON RequestApplications (Username)");
    }

    public override void Down()
    {
        Sql("DROP INDEX IX_Applications_Username");
    }
}

要定义多个键,请在每个键上放置[Key]和[Column(x)]属性

至于想要的名称,而不是id,我认为不应该在这些模型。在我看来,这将是一个数据投影,并且将是针对这些对象编写的查询的一部分

SecondSomething.Where(x=>x.IsActive).Select(x=>new MyProjection { Name = x.Sth.Name, //others}).ToList(); 

对于唯一约束,代码中没有要首先设置的属性。查看文章以了解更多信息。能否提供“创建SQL”以了解表及其约束和索引的外观。除了主键之外,不支持(目前)外键指向唯一列。
SecondSomething.Where(x=>x.IsActive).Select(x=>new MyProjection { Name = x.Sth.Name, //others}).ToList();