20

既存の DB スキーマには、一意の非プライマリ キーと、それらに依存するいくつかの外部キーがあります。

Entity Framework v4で、主キーではない一意のキーを定義することはできますか? どのように?

4

5 に答える 5

11

次の MSDN ブログ投稿も参照してください: http://blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx。簡単に言えば、これは V4 ではサポートされていませんが、EF チームは将来のリリースでサポートする計画があるようです。

于 2011-04-04T22:46:45.760 に答える
10

少し前に同じ問題に遭遇しました。

いくつかのテーブルを含むデータベースが与えられました (以下を参照)。

 public class ClinicDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Doctor> Doctors { get; set; }
    public DbSet<Patient> Patients { get; set; }
    public DbSet<Secretary> Secretarys { get; set; }
    public DbSet<Disease> Diseases { get; set; }
    public DbSet<Consultation> Consultations { get; set; }
    public DbSet<Administrator> Administrators { get; set; }
}

Users テーブルは次のように記述されていました。

public class User
{
    [Key]
    public Guid UserId { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }

    public string Name { get; set; }
    public string Surname { get; set; }
    public string IdentityCardNumber { get; set; }
    public string PersonalNumericalCode { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string Address { get; set; }
}

次に、すべての「UserName」属性が一意であることを確認するよう求められました。そのための注釈がないため、回避策を見つけなければなりませんでした。そして、ここにあります:

まず、データベース コンテキスト クラスを次のように変更しました。

public class ClinicDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Doctor> Doctors { get; set; }
    public DbSet<Patient> Patients { get; set; }
    public DbSet<Secretary> Secretarys { get; set; }
    public DbSet<Disease> Diseases { get; set; }
    public DbSet<Consultation> Consultations { get; set; }
    public DbSet<Administrator> Administrators { get; set; }

    public class Initializer : IDatabaseInitializer<ClinicDbContext>
    {
        public void InitializeDatabase(ClinicDbContext context)
        {
            if (!context.Database.Exists() || !context.Database.CompatibleWithModel(false))
            {
                if (context.Database.Exists())
                {
                    context.Database.Delete();
                }
                context.Database.Create();

                context.Database.ExecuteSqlCommand("CREATE INDEX IX_Users_UserName ON dbo.Users ( UserName )");
            }
        }
    }
}

上記の重要な部分は、必要な列に一意のインデックスを強制することによってテーブルを変更するsql コマンドです。この場合は UserName です。

このメソッドは、たとえば次のようにメイン クラスから呼び出すことができます。

class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer<ClinicDbContext>(new ClinicDbContext.Initializer());

        using (var ctx = new ClinicDbContext())
        {
            Console.WriteLine("{0} products exist in the database.", ctx.Users.Count());
        }

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

Programクラスを実行しようとしたときに発生した最後の問題は次のとおりです。

この問題を解決するために、UserName 属性に[MaxLength(250)]注釈を追加しました。

最終的に User クラスは次のようになります。

public class User
{
    [Key]
    public Guid UserId { get; set; }

    [MaxLength(250)]
    public string UserName { get; set; }

    public string Password { get; set; }

    public string Name { get; set; }
    public string Surname { get; set; }
    public string IdentityCardNumber { get; set; }
    public string PersonalNumericalCode { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string Address { get; set; }
}

それがあなたの問題も解決することを願っています!

于 2013-05-11T10:47:29.900 に答える
8

次のテーブルを定義しようとしました。

  • 注文 [ID (プライマリ、ID)、ClientName、FriendlyOrderNum (一意)]
  • OrderItems [Id (プライマリ、ID)、FriendlyOrderNum (一意)、ItemName]

そして、OrderItems.FriendlyOrderNum (Mant) から Orders.FriendlyOrderNum (1) への外部キー マッピング。

一意の非主キーが可能な場合、次の SSDL が機能するはずです。

<Schema Namespace="EfUkFk_DbModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
    <EntityContainer Name="EfUkFk_DbModelStoreContainer">
      <EntitySet Name="OrderItems" EntityType="EfUkFk_DbModel.Store.OrderItems" store:Type="Tables" Schema="dbo" />
      <EntitySet Name="Orders" EntityType="EfUkFk_DbModel.Store.Orders" store:Type="Tables" Schema="dbo" />
    </EntityContainer>
    <EntityType Name="OrderItems">
      <Key>
        <PropertyRef Name="RowId" />
      </Key>
      <Property Name="RowId" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" />
      <Property Name="OrderNum" Type="char" Nullable="false" MaxLength="5" />
      <Property Name="ItemName" Type="varchar" MaxLength="100" />
    </EntityType>
    <!--Errors Found During Generation:
  warning 6035: The relationship 'FK_OrderItems_Orders' has columns that are not part of the key of the table on the primary side of the relationship. The relationship was excluded.
  -->
    <EntityType Name="Orders">
      <Key>
        <PropertyRef Name="RowId" />
      </Key>
      <Property Name="RowId" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" />
      <Property Name="ClientName" Type="varchar" MaxLength="100" />
      <Property Name="OrderNum" Type="char" Nullable="false" MaxLength="5" />
    </EntityType>

  <!-- AsafR -->
    <Association Name="FK_OrderItems_Orders">
      <End Role="Orders" Type="EfUkFk_DbModel.Store.Orders" Multiplicity="1">
      </End>
      <End Role="OrderItems" Type="EfUkFk_DbModel.Store.OrderItems" Multiplicity="*" />
      <ReferentialConstraint>
        <Principal Role="Orders">
          <PropertyRef Name="OrderNum" />
        </Principal>
        <Dependent Role="OrderItems">
          <PropertyRef Name="OrderNum" />
        </Dependent>
      </ReferentialConstraint>
    </Association>
  </Schema></edmx:StorageModels>

そうではありません。<EntityType> に <key> 要素をさらに追加することもできません。

私の結論は、プライマリ以外の一意のキーは EF 4 ではサポートされていないということです。

于 2010-04-13T08:27:36.280 に答える
3

DataAnnotations 検証も使用できます。

を継承するこの( UniqueAttribute) クラスを作成しましValidationAttributeた。プロパティに適用すると、検証中にその列の値が取得され、検証されます。

ここから未加工のコードを入手できます。

于 2013-04-14T14:01:51.763 に答える