2012-10-31 52 views
0

我正在使用Code First編寫一個模型,其中包含兩個實體:'Action'和'Permission'。Code First One to One relationship

每個權限都指向了一個Action。 沒有兩個權限可能指向相同的操作。 一個動作可能存在,而不會被許可指向。

操作不應該意識到權限。

我的代碼是:

public Action 
{ 
    public Guid Id {get; set;} 
    public string Name {get; set;} 
} 

public Permission 
{ 
    public Guid Id {get; set;} 
    public string Name {get; set;} 

    public Action Action {get; set;} 
} 

而且,我用流利的API配置權限:

modelBuilder.Entity<Permission>.HasRequired(p => p.Action).WithOptional() 
      .WillCascadeOnDelete(); 

當我嘗試刪除的動作,我得到以下錯誤:

"Adding a relationship with an entity which is in the Deleted state is not allowed".

I t先刪除權限,然後刪除操作。對於這一點,我需要獲取給定的動作ID的權限,但我得到這個錯誤:

var permission = (from p in context.Permissions.Include(p => p.Action) 
        where p.Action.Id == actionId 
        select p).Single(); 

"Indexed properties are not supported"

我在做什麼錯?對此進行建模有更好的方法嗎?

謝謝! 尼爾

回答

0

三點建議,我沒有嘗試過的第一個,看看它的工作原理:

建議#1 與FK屬性添加一個外鍵模式,如:

public Permission 
{ 
    public Guid Id {get; set;} 
    public string Name {get; set;} 

    [ForeignKey("Action")] 
    public int ActionId {get; set;} 
    public Action Action {get; set;} 
} 

然後嘗試:

var permission = (from p in context.Permissions.Include(p => p.Action) 
       where p.ActionId == actionId 
       select p).Single(); 

建議#2可以在這裏找到:

EF 4.1: Difference between .WithMany() and .WithOptional() ?

建議#3

我們有一個類似的模型,但是我們使雙方意識到彼此的存在。爲什麼不希望在Action中包含Permission導航屬性有充分的理由嗎?你可以這樣做:

public Action 
{ 
    public Guid Id {get; set;} 
    public string Name {get; set;} 

    // notice the FK is nullable 
    public int? PermissionId {get; set;} 
    public Permission {get; set;} 
} 

下面是我們如何構建我們的模型中,每個文檔具有爲DocumentType一個1..1關係:

public class Document 
{ 

#region " Mutually exclusive document type relationships, necessary for setting up shared primary key in db " 
public BindingAgreement BindingAgreement { get; set; } 
public CeoLetter CeoLetter { get; set; } 
public Email Email { get; set; } 
.... 
#endregion 
//other code 
} 

Public class BindingAgreement 
{ 
    public Document {get;set;} 
    // other code 
} 

Public class CeoLetter 
{ 
    public Document {get;set;} 
    // other code 
} 

Public class Email 
{ 
    public Document {get;set;} 
    // other code 
} 

然後在我的模型生成我這樣做:

//Binding Agreement 
    modelBuilder.Entity<BindingAgreement>().HasRequired(c => c.Document); 

    //Ceo Letter 
    modelBuilder.Entity<CeoLetter>().HasRequired(c => c.Document); 

    //Email 
    modelBuilder.Entity<Email>().HasRequired(c => c.Document); 

除此之外,我用我的主鍵ints,但我不明白爲什麼這是一個因素。

我也不確定你需要刪除級聯如果你可以有一個沒有權限的行動。如果你沒有一個沒有權限的Action,你需要用(Has/With)Required流利地圖或者以一種允許CF解釋你的意圖的方式明確地構建你的代碼。

我會在稍後嘗試前兩個建議並讓您知道我的結果。