4

i'm working with an existing database, looking to update to asp.net MVC 4. I'm having difficulty creading the models for two of the tables. The Rule and RuleApply table.

I hope to query it using something similar to this:

var rules = db.Rules.Include("RulesApply").Where(t => t.rule_active == 1).ToList();

The RuleApply table has no primary key (it's simply used as a lookup table) - so when I try to compile, I get the error:

EntityType 'RuleApply' has no key defined. Define the key for this EntityType.

Is there any way I can link the Rule.id with the RuleApply.rule_id? Or doe the existing table, have to have a primary key added, to allow me to use EF/Linq etc?

namespace emc.Models
{
public class Rule
{
    [Key]
    public int id { get; set; }
    public int type_id { get; set; }
    public int rule_active { get; set; }
    public DateTime rule_start { get; set; }
    public DateTime rule_end { get; set; }
    public virtual ICollection<RuleApply> RulesApply { get; set; }
}

public class RuleApply
{
    public int type_id { get; set; }
    public int rule_id { get; set; }
    public virtual Rule Rule { get; set; }

}
}

Thanks for any advice,

Mark

2 Answers 2

5

Just add key property to RuleApply type (Id will be treated as Key by convention, you don't need to mark property with such name with KeyAttribute). Also use ForeignKey attribute to link rule_id property with Rule:

public class RuleApply
{
    public int Id; // entity should have primary key
    public int type_id { get; set; }
    public int rule_id { get; set; }
    [ForeignKey("rule_id")]
    public virtual Rule Rule { get; set; } 
}

Or make composite key from existing properties:

public class RuleApply
{
    [Key, Column(Order=0)]
    public int type_id { get; set; }
    [Key, Column(Order=1)]
    public int rule_id { get; set; }
    [ForeignKey("rule_id")]
    public virtual Rule Rule { get; set; }    
}

BTW in C# we use PascalCase naming for properties.

Sign up to request clarification or add additional context in comments.

Comments

1

Is there some reason that you can't make the combination of type_id and rule_id the primary key of RuleApply? Things will run faster if those fields are indexed, which a primary key will do.

I'm not 100% sure, since all my tables usually have keys, but I believe EF will balk at updating the table if it has no primary key. It won't know how to tell one record from another.

You can, however, indicate in EF that type_id and rule_id are the primary key of RuleApply even without making it so in the underlying database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.