Reputation: 27585
I have these entities:
public class User {
public string Username { get; set; }
// OtherProperties
}
public class Page {
public string Username { get; set; }
// OtherProperties
}
OtherProperties
are completely different in each entity from another one. But, Username
s should be unique, no matter where they belong. I mean if there is a User
with Username = a
, none of other User
s or Page
s can have this Username
. How would you handle this? Is it a good idea to have a 3th entity e.g. a
class Username { string Name { get; set; } }
considering this fact that it is just a simple-single property?
UPDATE: more explain:
User
is a completely independent different entity from Page
. But both of them have a property named Username
which should be unique in entire application.
Upvotes: 0
Views: 128
Reputation: 48550
Yes, your approach is good. Create a third class Username
and add a property of it in your first two classes. Like this
class UserName
{
string Name { get; set; }
}
public class User
{
public Username UName { get; set; }
// OtherProperties
}
public class Page
{
public UserName UName { get; set; }
// OtherProperties
}
Changed property name because class Name and property name was same. You can have what suits you best.
Back to problem.
Moreover tomorrow if you want to add any other details about User Name, then you have to add a property in your UserName
and your code in User and Page will not require any change.
Upvotes: 1
Reputation: 1655
If you want to have unique user names in many classes then you should implement 3rd table with unique usernames which will be FKyed to all of the tables containing username property (column). For this task you can use class attributes or FluentAPI. As my experience told me it is better to use FluentAPI as attributes approach not always provide expected results.
For example smth like this:
public class Username
{
[Index(IsUnique = true)]
public int Id {get;set;}
[Index(IsUnique = true)]
public string Name {get;set;}
public virtual ICollection<Page> PagesList{ get; set; }
}
public class Page {
public int UsernameId { get; set; }
// OtherProperties
public virtual string Username {get;set;}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//one-to-many
modelBuilder.Entity<Page>().HasRequired<Username>(s => s.Username)
.WithMany(s => s.PagesList)
.WillCascadeOnDelete(true);
}
More details on FluentAPI unique keys: Unique keys in Entity Framework 4
More details on implementing FKs: http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx
Upvotes: 0