2013-02-11 69 views
1

我有这样的事情:有没有像主键和辅助键?

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;} 
} 

是否有实现这一目标的方法吗?

+0

对于唯一约束,没有要在代码中设置的属性。检查[实体框架代码中的唯一约束优先](http://www.it2y.info/sql-server/unique-constraint-in-entity-framework-code-first.html)文章以获取更多信息。 – 2013-02-11 12:58:40

+0

您能否为表及其约束和索引的外观提供“创建SQL”? – 2013-02-11 13:09:40

+0

对于除主键以外的唯一列,外键还不支持(尚)。 – 2013-02-11 14:05:54

回答

0
HasRequired(x => x.sthName) 
    .WithMany() //I assume 
    .Map(x => x.MapKey("Sth")); 
0

像格特阿诺德说,对于上的代码首先定义指标没有直接的支持,但如果你使用的迁移,你可以直接调用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"); 
    } 
} 
0

定义多个键,你把每个[Key]和[Column(x)]属性。

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

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