开发者

Best approach for my EF 'DataBase'

I've been a few weeks working on a web project, amd mostly thinking how would I implement data layer. I chosed Entity Framework 4.1, code first model.

So, among lot of other entities , think of PLAYER who has N CHARACTER, that can be in 0..1 GUILD

public class Player
{
    public int Id { get; set; }
    public string Login { get; set; }
    public string Password { get; set; }
    public bool IsLogged { get; set; }
    public DateTime LastActivity { get; set; }
    public DateTime LastLogin { get; set; }
    public DateTime LastLogout { get; set; }
    public string DisplayName { get; set; }
    public string DefaultImage { get; set; }

    public virtual Board Board { get; set; }
    public virtual PlayerData PlayerData { get; set; }
    public virtual ICollection<Character> Characters { get; set; }
}
public class Guild
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string DefaultImage { get; set; }

    public virtual ICollection<Character> Characters { get; set; }
}
public class Character
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual Player Player { get; set; }
    public virtual Guild Guild { get; set; }
    public virtual GuildRank GuildRank { get; set; }
    public virtual Game Game { get; set; }
}

As you can see, there a lot more entities and relationships, but this will work.

Well it does not, this code:

Character character = mod.Characters.Where(c => c.Player == player).FirstOrDefault();

Throws an exception:

Unable开发者_高级运维 to create a constant value of type 'DataObjects.Player'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

I don't understand why.

I also tried with using [Key] and [ForeingKey] attributes, but I can't find them! :S (though the where in System.Data.Entity.dll, but the don't).

So after so many errors, I started to think maybe I got the whole thing wrong...

Any ideas on how to fix the error, or to go in other direction?

Thanks in advance.


This is stupidity in EF. You cannot compare Player directly. You must compare Ids so your query can be rewritten to:

int playerId = player.Id;
Character character = mod.Characters.FirstOrDefault(c => c.Player.Id == playerId);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜