Reputation: 4265
First, is there a way to tell EF 4.1 that a column needs to be unique by using either data annotations or the fluent API?
Second, regarding navigation properties, I have have 2 classes Document and User. In the document class I have a property for the OwnerId (UserId) and a property for Owner (User). How do I tell EF 4.1 that the OwnerId is really UserId and Owner is a navigation property back to User?
The Document Class:
public abstract class Document: BaseEntity
{
public bool IsActive { get; set; }
public string Description { get; set; }
//The UserId
public Guid OwnerId { get; set; }
//The User
public User Owner { get; set; }
}
Upvotes: 3
Views: 2642
Reputation: 364349
Entity framework doesn't support unique keys at all so the answer to your first question is no.
OwnerId
should be recognized as foreign key for Owner
automatically unless you map to existing database where the foreign key is named differently. In such case you can use for example:
public abstract class Document: BaseEntity
{
public bool IsActive { get; set; }
public string Description { get; set; }
[Column("UserId"), ForeignKey("Owner")]
public Guid OwnerId { get; set; }
public User Owner { get; set; }
}
Foreign key data annotation is probably not needed but you can use it to explicitly pair your FK property with navigation property.
In fluent mapping you can use:
modelBuilder.Entity<Document>()
.Property(d => d.OwnerId)
.HasColumnName("UserId");
modelBuilder.Entity<Document>()
.HasRequired(d => d.Owner)
.WithMany(...)
.HasForeignKey(d => d.OwnerId);
Upvotes: 5